array_api._2025_12 module¶
- class array_api._2025_12.Array[source]¶
Bases:
Protocol,Generic- property T: Self¶
Transpose of the array.
The array instance must be two-dimensional. If the array instance is not two-dimensional, an error should be raised.
- Returns:
out – two-dimensional array whose first and last dimensions (axes) are permuted in reverse order relative to original array. The returned array must have the same data type as the original array.
- Return type:
array
Note
Limiting the transpose to two-dimensional arrays (matrices) deviates from the NumPy et al practice of reversing all axes for arrays having more than two-dimensions. This is intentional, as reversing all axes was found to be problematic (e.g., conflicting with the mathematical definition of a transpose which is limited to matrices; not operating on batches of matrices; et cetera). In order to reverse all axes, one is recommended to use the functional
permute_dimsinterface found in this specification.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- property device: TDevice¶
Hardware device the array data resides on.
- Returns:
out – a
deviceobject (see device-support).- Return type:
- property dtype: TDtype¶
Data type of the array elements.
- Returns:
out – array data type.
- Return type:
- property mT: Self¶
Transpose of a matrix (or a stack of matrices).
If an array instance has fewer than two dimensions, an error should be raised.
- Returns:
out – array whose last two dimensions (axes) are permuted in reverse order relative to original array (i.e., for an array instance having shape
(..., M, N), the returned array must have shape(..., N, M)). The returned array must have the same data type as the original array.- Return type:
array
- property ndim: int¶
Number of array dimensions (axes).
- Returns:
out – number of array dimensions (axes).
- Return type:
int
- property shape: tuple[int | None, ...]¶
Array dimensions.
- Returns:
out – array dimensions. An array dimension must be
Noneif and only if a dimension is unknown.- Return type:
Tuple[Optional[int], …]
Note
For array libraries having graph-based computational models, array dimensions may be unknown due to data-dependent operations (e.g., boolean indexing;
A[:, B > 0]) and thus cannot be statically resolved without knowing array contents.Note
The returned value should be a tuple; however, where warranted, an array library may choose to return a custom shape object. If an array library returns a custom shape object, the object must be immutable, must support indexing for dimension retrieval, and must behave similarly to a tuple.
- property size: int | None¶
Number of elements in an array.
Note
This must equal the product of the array’s dimensions.
- Returns:
out – number of elements in an array. The returned value must be
Noneif and only if one or more array dimensions are unknown.- Return type:
Optional[int]
Note
For array libraries having graph-based computational models, an array may have unknown dimensions due to data-dependent operations.
- to_device(device: TDevice, /, *, stream: int | Any | None = None) Self[source]¶
Copy the array from the device on which it currently resides to the specified
device.- Parameters:
self – array instance.
device (device) – a
deviceobject (see device-support).stream (Optional[Union[int, Any]]) – stream object to use during copy. In addition to the types supported in
array.__dlpack__(), implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable.
- Returns:
out – an array with the same data and data type as
selfand located on the specifieddevice.- Return type:
array
Notes
When a provided
deviceobject corresponds to the same device on which an array instance resides, implementations may choose to perform an explicit copy or returnself.If
streamis provided, the copy operation should be enqueued on the providedstream; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming array library’s documentation.
Changed in version 2023.12: Clarified behavior when a provided
deviceobject corresponds to the device on which an array instance resides.
- class array_api._2025_12.ArrayNamespace(*args, **kwargs)[source]¶
Bases:
Protocol,Generic- Device: TDevice¶
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- abs: abs[TArray]¶
Calculates the absolute value for each element
x_iof the input arrayx.For real-valued input arrays, the element-wise result has the same magnitude as the respective element in
xbut has positive sign.Note
For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent.
Note
For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number \(z = a + bj\) is computed as
\[\operatorname{abs}(z) = \sqrt{a^2 + b^2}\]Note
For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation.
- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the absolute value of each element in
x. Ifxhas a real-valued data type, the returned array must have the same data type asx. Ifxhas a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type).- Return type:
array
Notes
Special Cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis-0, the result is+0.If
x_iis-infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+infinityor-infinityandbis any value (includingNaN), the result is+infinity.If
ais any value (includingNaN) andbis either+infinityor-infinity, the result is+infinity.If
ais either+0or-0, the result is equal toabs(b).If
bis either+0or-0, the result is equal toabs(a).If
aisNaNandbis a finite number, the result isNaN.If
ais a finite number andbisNaN, the result isNaN.If
aisNaNandbisNaN, the result isNaN.
Changed in version 2022.12: Added complex data type support.
- acos: acos[TArray]¶
Calculates an implementation-dependent approximation of the principal value of the inverse cosine for each element
x_iof the input arrayx.Each element-wise result is expressed in radians.
Note
The principal value of the arc cosine of a complex number \(z\) is
\[\operatorname{acos}(z) = \frac{1}{2}\pi + j\ \ln(zj + \sqrt{1-z^2})\]For any \(z\),
\[\operatorname{acos}(z) = \pi - \operatorname{acos}(-z)\]Note
For complex floating-point operands,
acos(conj(x))must equalconj(acos(x)).Note
The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty, -1)\) and \((1, \infty)\) of the real axis.
Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval \([0, \pi]\) along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the inverse cosine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis greater than1, the result isNaN.If
x_iis less than-1, the result isNaN.If
x_iis1, the result is+0.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result isπ/2 - 0j.If
ais either+0or-0andbisNaN, the result isπ/2 + NaN j.If
ais a finite number andbis+infinity, the result isπ/2 - infinity j.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais-infinityandbis a positive (i.e., greater than0) finite number, the result isπ - infinity j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+0 - infinity j.If
ais-infinityandbis+infinity, the result is3π/4 - infinity j.If
ais+infinityandbis+infinity, the result isπ/4 - infinity j.If
ais either+infinityor-infinityandbisNaN, the result isNaN ± infinity j(sign of the imaginary component is unspecified).If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result isNaN - infinity j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- acosh: acosh[TArray]¶
Calculates an implementation-dependent approximation to the inverse hyperbolic cosine for each element
x_iof the input arrayx.Note
The principal value of the inverse hyperbolic cosine of a complex number \(z\) is
\[\operatorname{acosh}(z) = \ln(z + \sqrt{z+1}\sqrt{z-1})\]For any \(z\),
\[\operatorname{acosh}(z) = \frac{\sqrt{z-1}}{\sqrt{1-z}}\operatorname{acos}(z)\]or simply
\[\operatorname{acosh}(z) = j\ \operatorname{acos}(z)\]in the upper half of the complex plane.
Note
For complex floating-point operands,
acosh(conj(x))must equalconj(acosh(x)).Note
The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment \((-\infty, 1)\) of the real axis.
Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval \([0, \infty)\) along the real axis and in the interval \([-\pi j, +\pi j]\) along the imaginary axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type.
- Returns:
out – an array containing the inverse hyperbolic cosine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than1, the result isNaN.If
x_iis1, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result is+0 + πj/2.If
ais a finite number andbis+infinity, the result is+infinity + πj/2.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais+0andbisNaN, the result isNaN ± πj/2(sign of imaginary component is unspecified).If
ais-infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + πj.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0j.If
ais-infinityandbis+infinity, the result is+infinity + 3πj/4.If
ais+infinityandbis+infinity, the result is+infinity + πj/4.If
ais either+infinityor-infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is+infinity + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- add: add[TArray]¶
Calculates the sum for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float, complex]) – first input array. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – second input array. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise sums. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For real-valued floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis+infinityandx2_iis-infinity, the result isNaN.If
x1_iis-infinityandx2_iis+infinity, the result isNaN.If
x1_iis+infinityandx2_iis+infinity, the result is+infinity.If
x1_iis-infinityandx2_iis-infinity, the result is-infinity.If
x1_iis+infinityandx2_iis a finite number, the result is+infinity.If
x1_iis-infinityandx2_iis a finite number, the result is-infinity.If
x1_iis a finite number andx2_iis+infinity, the result is+infinity.If
x1_iis a finite number andx2_iis-infinity, the result is-infinity.If
x1_iis-0andx2_iis-0, the result is-0.If
x1_iis-0andx2_iis+0, the result is+0.If
x1_iis+0andx2_iis-0, the result is+0.If
x1_iis+0andx2_iis+0, the result is+0.If
x1_iis either+0or-0andx2_iis a nonzero finite number, the result isx2_i.If
x1_iis a nonzero finite number andx2_iis either+0or-0, the result isx1_i.If
x1_iis a nonzero finite number andx2_iis-x1_i, the result is+0.In the remaining cases, when neither
infinity,+0,-0, nor aNaNis involved, and the operands have the same mathematical sign or have different magnitudes, the sum must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported round mode. If the magnitude is too large to represent, the operation overflows and the result is an infinity of appropriate mathematical sign.
Note
Floating-point addition is a commutative operation, but not always associative.
For complex floating-point operands, addition is defined according to the following table. For real components
aandcand imaginary componentsbandd,c
dj
c + dj
a
a + c
a + dj
(a+c) + dj
bj
c + bj
(b+d)j
c + (b+d)j
a + bj
(a+c) + bj
a + (b+d)j
(a+c) + (b+d)j
For complex floating-point operands, real-valued floating-point special cases must independently apply to the real and imaginary component operations involving real numbers as described in the above table. For example, let
a = real(x1_i),b = imag(x1_i),c = real(x2_i),d = imag(x2_i), andIf
ais-0andcis-0, the real component of the result is-0.Similarly, if
bis+0anddis-0, the imaginary component of the result is+0.
Hence, if
z1 = a + bj = -0 + 0jandz2 = c + dj = -0 - 0j, the result ofz1 + z2is-0 + 0j.Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- all: all[TArray]¶
Tests whether all input array elements evaluate to
Truealong a specified axis.- Parameters:
x (array) – input array.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid
axismust be an integer on the interval[-N, N), whereNis the number of axes inx. If anaxisis specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last axis (where-1refers to the last axis). If provided an invalidaxis, the function must raise an exception. Default:None.keepdims (bool) – If
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result. Otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of
bool.- Return type:
array
Notes
Positive infinity, negative infinity, and NaN must evaluate to
True.If
xhas a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate toTrue.If
xis an empty array or the size of the axis along which to evaluate elements is zero, the test result must beTrue.
Changed in version 2022.12: Added complex data type support.
- any: any[TArray]¶
Tests whether any input array element evaluates to
Truealong a specified axis.- Parameters:
x (array) – input array.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid
axismust be an integer on the interval[-N, N), whereNis the number of axes inx. If anaxisis specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where-1refers to the last axis). If provided an invalidaxis, the function must raise an exception. Default:None.keepdims (bool) – If
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result. Otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of
bool.- Return type:
array
Notes
Positive infinity, negative infinity, and NaN must evaluate to
True.If
xhas a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate toTrue.If
xis an empty array or the size of the axis along which to evaluate elements is zero, the test result must beFalse.
Changed in version 2022.12: Added complex data type support.
- arange: arange[TArray, TDtype, TDevice]¶
Returns evenly spaced values within the half-open interval
[start, stop)as a one-dimensional array.- Parameters:
start (Union[int, float]) – if
stopis specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). Ifstopis not specified, the default starting value is0.stop (Optional[Union[int, float]]) – the end of the interval. Default:
None.step (Union[int, float]) – the distance between two adjacent elements (
out[i+1] - out[i]). Must not be0; may be negative, this results in an empty array ifstop >= start. Default:1.dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be inferred fromstart,stopandstep. If those are all integers, the output array dtype must be the default integer dtype; if one or more have typefloat, then the output array dtype must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
Note
This function cannot guarantee that the interval does not include the
stopvalue in those cases wherestepis not an integer and floating-point rounding errors affect the length of the output array.- Returns:
out – a one-dimensional array containing evenly spaced values. The length of the output array must be
ceil((stop-start)/step)ifstop - startandstephave the same sign, and length0otherwise.- Return type:
array
- argmax: argmax[TArray]¶
Returns the indices of the maximum values along a specified axis.
When the maximum value occurs multiple times, only the indices corresponding to the first occurrence are returned.
- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (Optional[int]) – axis along which to search. If
None, the function must return the index of the maximum value of the flattened array. If notNone, a valid axis must be an integer on the interval[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if
axisisNone, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array must have be the default array index data type.- Return type:
array
Notes
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
- argmin: argmin[TArray]¶
Returns the indices of the minimum values along a specified axis.
When the minimum value occurs multiple times, only the indices corresponding to the first occurrence are returned.
- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (Optional[int]) – axis along which to search. If
None, the function must return the index of the minimum value of the flattened array. If notNone, a valid axis must be an integer on the interval[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if
axisisNone, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array must have the default array index data type.- Return type:
array
Notes
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
- argsort: argsort[TArray]¶
Returns the indices that sort an array
xalong a specified axis.- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (int) – axis along which to sort. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:-1.descending (bool) – sort order. If
True, the returned indices must sortxin descending order (by value). IfFalse, the returned indices must sortxin ascending order (by value). Default:False.stable (bool) – sort stability. If
True, the returned indices must maintain the relative order ofxvalues which compare as equal. IfFalse, the returned indices may maintain the relative order ofxvalues which compare as equal (i.e., the relative order ofxvalues which compare as equal is implementation-dependent). Default:True.
- Returns:
out – an array of indices. The returned array must have the same shape as
x. The returned array must have the default array index data type.- Return type:
array
Notes
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
- asarray: asarray[TArray, TDtype, TDevice]¶
Convert the input to an array.
- Parameters:
obj (Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol]) –
object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol.
Tip
An object supporting the buffer protocol can be turned into a memoryview through
memoryview(obj).dtype (Optional[dtype]) –
output array data type. If
dtypeisNone, the output array data type must be inferred from the data type(s) inobj. If all input values are Python scalars, then, in order of precedence,if all values are of type
bool, the output data type must bebool.if all values are of type
intor are a mixture ofboolandint, the output data type must be the default integer data type.if one or more values are
complexnumbers, the output data type must be the default complex floating-point data type.if one or more values are
floats, the output data type must be the default real-valued floating-point data type.
Default:
None.device (Optional[device]) – device on which to place the created array. If
deviceisNoneandobjis an array, the output array device must be inferred fromobj. Default:None.copy (Optional[bool]) – boolean indicating whether or not to copy the input. If
True, the function must always copy (see copy-keyword-argument). IfFalse, the function must never copy for input which supports the buffer protocol and must raise aValueErrorin case a copy would be necessary. IfNone, the function must reuse existing memory buffer if possible and copy otherwise. Default:None.
- Returns:
out – an array containing the data from
obj.- Return type:
array
Notes
If
objis a sequence with some elements being arrays, behavior is unspecified and thus implementation-defined. Conforming implementations may perform a conversion or raise an exception. To join a sequence of arrays along a new axis, seestack().If
dtypeis notNone, then array conversions should obey type-promotion rules. Conversions not specified according to type-promotion rules may or may not be permitted by a conforming array library. To perform an explicit cast, usearray_api.astype().If an input value exceeds the precision of the resolved output array data type, behavior is unspecified and thus implementation-defined.
Changed in version 2022.12: Added complex data type support.
- asin: asin[TArray]¶
Calculates an implementation-dependent approximation of the principal value of the inverse sine for each element
x_iof the input arrayx.Each element-wise result is expressed in radians.
Note
The principal value of the arc sine of a complex number \(z\) is
\[\operatorname{asin}(z) = -j\ \ln(zj + \sqrt{1-z^2})\]For any \(z\),
\[\operatorname{asin}(z) = \operatorname{acos}(-z) - \frac{\pi}{2}\]Note
For complex floating-point operands,
asin(conj(x))must equalconj(asin(x)).Note
The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty, -1)\) and \((1, \infty)\) of the real axis.
Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval \([-\pi/2, +\pi/2]\) along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the inverse sine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis greater than1, the result isNaN.If
x_iis less than-1, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
-1j * asinh(x*1j).Changed in version 2022.12: Added complex data type support.
- asinh: asinh[TArray]¶
Calculates an implementation-dependent approximation to the inverse hyperbolic sine for each element
x_iin the input arrayx.Note
The principal value of the inverse hyperbolic sine of a complex number \(z\) is
\[\operatorname{asinh}(z) = \ln(z + \sqrt{1+z^2})\]For any \(z\),
\[\operatorname{asinh}(z) = \frac{\operatorname{asin}(zj)}{j}\]Note
For complex floating-point operands,
asinh(conj(x))must equalconj(asinh(x))andasinh(-z)must equal-asinh(z).Note
The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty j, -j)\) and \((j, \infty j)\) of the imaginary axis.
Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval \([-\pi j/2, +\pi j/2]\) along the imaginary axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type.
- Returns:
out – an array containing the inverse hyperbolic sine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais+0andbis+0, the result is+0 + 0j.If
ais a positive (i.e., greater than0) finite number andbis+infinity, the result is+infinity + πj/2.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0j.If
ais+infinityandbis+infinity, the result is+infinity + πj/4.If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis a nonzero finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is±infinity + NaN j(sign of the real component is unspecified).If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- astype: astype[TArray, TDtype, TDevice]¶
Copies an array to a specified data type irrespective of type-promotion rules.
Note
Casting floating-point
NaNandinfinityvalues to integral data types is not specified and is implementation-dependent.Note
Casting a complex floating-point array to a real-valued data type should not be permitted.
Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array
x,astype(x)equalsastype(real(x))). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point arrayx,astype(x)andastype(real(x))versus onlyastype(imag(x))). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type.Note
When casting a boolean input array to a real-valued data type, a value of
Truemust cast to a real-valued number equal to1, and a value ofFalsemust cast to a real-valued number equal to0.When casting a boolean input array to a complex floating-point data type, a value of
Truemust cast to a complex number equal to1 + 0j, and a value ofFalsemust cast to a complex number equal to0 + 0j.Note
When casting a real-valued input array to
bool, a value of0must cast toFalse, and a non-zero value must cast toTrue.When casting a complex floating-point array to
bool, a value of0 + 0jmust cast toFalse, and all other values must cast toTrue.- Parameters:
x (array) – array to cast.
dtype (dtype) – desired data type.
copy (bool) – specifies whether to copy an array when the specified
dtypematches the data type of the input arrayx. IfTrue, a newly allocated array must always be returned (see copy-keyword-argument). IfFalseand the specifieddtypematches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default:True.device (Optional[device]) – device on which to place the returned array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the specified data type. The returned array must have the same shape as
x.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Added device keyword argument support.
- atan: atan[TArray]¶
Calculates an implementation-dependent approximation of the principal value of the inverse tangent for each element
x_iof the input arrayx.Each element-wise result is expressed in radians.
Note
The principal value of the inverse tangent of a complex number \(z\) is
\[\operatorname{atan}(z) = -\frac{\ln(1 - zj) - \ln(1 + zj)}{2}j\]Note
For complex floating-point operands,
atan(conj(x))must equalconj(atan(x)).Note
The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty j, -j)\) and \((+j, \infty j)\) of the imaginary axis.
Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval \([-\pi/2, +\pi/2]\) along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the inverse tangent of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is an implementation-dependent approximation to+π/2.If
x_iis-infinity, the result is an implementation-dependent approximation to-π/2.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
-1j * atanh(x*1j).Changed in version 2022.12: Added complex data type support.
- atan2: atan2[TArray]¶
Calculates an implementation-dependent approximation of the inverse tangent of the quotient
x1/x2, having domain[-infinity, +infinity] x [-infinity, +infinity](where thexnotation denotes the set of ordered pairs of elements(x1_i, x2_i)) and codomain[-π, +π], for each pair of elements(x1_i, x2_i)of the input arraysx1andx2, respectively. Each element-wise result is expressed in radians.The mathematical signs of
x1_iandx2_idetermine the quadrant of each element-wise result. The quadrant (i.e., branch) is chosen such that each element-wise result is the signed angle in radians between the ray ending at the origin and passing through the point(1,0)and the ray ending at the origin and passing through the point(x2_i, x1_i).Note
Note the role reversal: the “y-coordinate” is the first function parameter; the “x-coordinate” is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second.
By IEEE 754 convention, the inverse tangent of the quotient
x1/x2is defined forx2_iequal to positive or negative zero and for either or both ofx1_iandx2_iequal to positive or negativeinfinity.- Parameters:
x1 (Union[array, int, float]) – input array corresponding to the y-coordinates. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – input array corresponding to the x-coordinates. Must be compatible with
x1(see broadcasting). Should have a real-valued floating-point data type.
- Returns:
out – an array containing the inverse tangent of the quotient
x1/x2. The returned array must have a real-valued floating-point data type determined by type-promotion.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis greater than0andx2_iis+0, the result is an implementation-dependent approximation to+π/2.If
x1_iis greater than0andx2_iis-0, the result is an implementation-dependent approximation to+π/2.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis+0andx2_iis+0, the result is+0.If
x1_iis+0andx2_iis-0, the result is an implementation-dependent approximation to+π.If
x1_iis+0andx2_iis less than0, the result is an implementation-dependent approximation to+π.If
x1_iis-0andx2_iis greater than0, the result is-0.If
x1_iis-0andx2_iis+0, the result is-0.If
x1_iis-0andx2_iis-0, the result is an implementation-dependent approximation to-π.If
x1_iis-0andx2_iis less than0, the result is an implementation-dependent approximation to-π.If
x1_iis less than0andx2_iis+0, the result is an implementation-dependent approximation to-π/2.If
x1_iis less than0andx2_iis-0, the result is an implementation-dependent approximation to-π/2.If
x1_iis greater than0,x1_iis a finite number, andx2_iis+infinity, the result is+0.If
x1_iis greater than0,x1_iis a finite number, andx2_iis-infinity, the result is an implementation-dependent approximation to+π.If
x1_iis less than0,x1_iis a finite number, andx2_iis+infinity, the result is-0.If
x1_iis less than0,x1_iis a finite number, andx2_iis-infinity, the result is an implementation-dependent approximation to-π.If
x1_iis+infinityandx2_iis a finite number, the result is an implementation-dependent approximation to+π/2.If
x1_iis-infinityandx2_iis a finite number, the result is an implementation-dependent approximation to-π/2.If
x1_iis+infinityandx2_iis+infinity, the result is an implementation-dependent approximation to+π/4.If
x1_iis+infinityandx2_iis-infinity, the result is an implementation-dependent approximation to+3π/4.If
x1_iis-infinityandx2_iis+infinity, the result is an implementation-dependent approximation to-π/4.If
x1_iis-infinityandx2_iis-infinity, the result is an implementation-dependent approximation to-3π/4.
Changed in version 2024.12: Added scalar argument support.
- atanh: atanh[TArray]¶
Calculates an implementation-dependent approximation to the inverse hyperbolic tangent for each element
x_iof the input arrayx.Note
The principal value of the inverse hyperbolic tangent of a complex number \(z\) is
\[\operatorname{atanh}(z) = \frac{\ln(1+z)-\ln(z-1)}{2}\]For any \(z\),
\[\operatorname{atanh}(z) = \frac{\operatorname{atan}(zj)}{j}\]Note
For complex floating-point operands,
atanh(conj(x))must equalconj(atanh(x))andatanh(-x)must equal-atanh(x).Note
The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty, 1]\) and \([1, \infty)\) of the real axis.
Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval \([-\pi j/2, +\pi j/2]\) along the imaginary axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type.
- Returns:
out – an array containing the inverse hyperbolic tangent of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than-1, the result isNaN.If
x_iis greater than1, the result isNaN.If
x_iis-1, the result is-infinity.If
x_iis+1, the result is+infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais+0andbis+0, the result is+0 + 0j.If
ais+0andbisNaN, the result is+0 + NaN j.If
ais1andbis+0, the result is+infinity + 0j.If
ais a positive (i.e., greater than0) finite number andbis+infinity, the result is+0 + πj/2.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+0 + πj/2.If
ais+infinityandbis+infinity, the result is+0 + πj/2.If
ais+infinityandbisNaN, the result is+0 + NaN j.If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is±0 + πj/2(sign of the real component is unspecified).If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- bitwise_and: bitwise_and[TArray]¶
Computes the bitwise AND of the underlying binary representation of each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- bitwise_invert: bitwise_invert[TArray]¶
Inverts (flips) each bit for each element
x_iof the input arrayx.- Parameters:
x (array) – input array. Should have an integer or boolean data type.
- Returns:
out – an array containing the element-wise results. The returned array must have the same data type as
x.- Return type:
array
- bitwise_left_shift: bitwise_left_shift[TArray]¶
Shifts the bits of each element
x1_iof the input arrayx1to the left by appendingx2_i(i.e., the respective element in the input arrayx2) zeros to the right ofx1_i.- Parameters:
x1 (Union[array, int]) – first input array. Should have an integer data type.
x2 (Union[array, int]) – second input array. Must be compatible with
x1(see broadcasting). Should have an integer data type. Each element must be greater than or equal to0.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- bitwise_or: bitwise_or[TArray]¶
Computes the bitwise OR of the underlying binary representation of each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- bitwise_right_shift: bitwise_right_shift[TArray]¶
Shifts the bits of each element
x1_iof the input arrayx1to the right according to the respective elementx2_iof the input arrayx2.Note
This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two.
- Parameters:
x1 (Union[array, int]) – first input array. Should have an integer data type.
x2 (Union[array, int]) – second input array. Must be compatible with
x1(see broadcasting). Should have an integer data type. Each element must be greater than or equal to0.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- bitwise_xor: bitwise_xor[TArray]¶
Computes the bitwise XOR of the underlying binary representation of each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- bool: TDtype¶
- broadcast_arrays: broadcast_arrays[TArray]¶
Broadcasts one or more arrays against one another.
- Parameters:
arrays (array) – an arbitrary number of to-be broadcasted arrays.
- Returns:
out – tuple of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array.
- Return type:
Tuple[array, …]
Notes
Changed in version 2025.12: Changed the return value from a List to a Tuple.
- broadcast_shapes: broadcast_shapes[()]¶
Broadcasts one or more shapes against one another.
- Parameters:
shapes (Tuple[Optional[int], ...]) – an arbitrary number of to-be broadcasted shapes.
- Returns:
out – a single broadcasted shape obtained by applying broadcasting rules (see broadcasting) to each of the input shapes against one another.
- Return type:
Tuple[Optional[int], …]
- Raises:
ValueError – If provided shapes which are not broadcast compatible (see broadcasting), a
ValueErrorshould be raised.
Notes
If not provided one or more arguments, the function must return an empty tuple.
Array-conforming libraries which build computation graphs (e.g., ndonnx and Dask) and which need to provide a mechanism for indicating dimensions of unknown size may accept non-integer values (e.g.,
None). For these libraries, dimensions of unknown size must be propagated to the returned shape.
- broadcast_to: broadcast_to[TArray]¶
Broadcasts an array to a specified shape.
- Parameters:
x (array) – array to broadcast. Must be capable of being broadcast to the specified
shape(see broadcasting). If the array is incompatible with the specified shape, the function must raise an exception.shape (Tuple[int, ...]) – array shape.
- Returns:
out (array) – an array having the specified shape. Must have the same data type as
x... versionchanged:: 2024.12 – Clarified broadcast behavior.
- can_cast: can_cast[TArray, TDtype]¶
Determines if one data type can be cast to another data type according to type promotion rules (see type-promotion).
- Parameters:
- Returns:
out –
Trueif the cast can occur according to type promotion rules (see type-promotion); otherwise,False.- Return type:
Notes
When
from_is a data type, the function must determine whether the data type can be cast to another data type according to the complete type promotion rules (see type-promotion) described in this specification, irrespective of whether a conforming array library supports devices which do not have full data type support.When
from_is an array, the function must determine whether the data type of the array can be cast to the desired data type according to the type promotion graph of the array device. As not all devices can support all data types, full support for type promotion rules (see type-promotion) may not be possible. Accordingly, the output ofcan_cast(array, dtype)may differ fromcan_cast(array.dtype, dtype).
Changed in version 2024.12: Required that the application of type promotion rules must account for device context.
- ceil: ceil[TArray]¶
Rounds each element
x_iof the input arrayxto the smallest (i.e., closest to-infinity) integer-valued number that is not less thanx_i.- Parameters:
x (array) – input array. Should have a real-valued data type.
- Returns:
out – an array containing the rounded result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
If
x_iis already integer-valued, the result isx_i.
For floating-point operands,
If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iisNaN, the result isNaN.
- clip: clip[TArray]¶
Clamps each element
x_iof the input arrayxto the range[min, max].- Parameters:
x (array) – input array. Should have a real-valued data type.
min (Optional[Union[int, float, array]]) – lower-bound of the range to which to clamp. If
None, no lower bound must be applied. Must be compatible withxandmax(see broadcasting). Should have the same data type asx. Default:None.max (Optional[Union[int, float, array]]) – upper-bound of the range to which to clamp. If
None, no upper bound must be applied. Must be compatible withxandmin(see broadcasting). Should have the same data type asx. Default:None.
- Returns:
out – an array containing element-wise results. The returned array should have the same data type as
x.- Return type:
array
Notes
This function is conceptually equivalent to
maximum(minimum(x, max), min)whenx,min, andmaxhave the same data type.If both
minandmaxareNone, the elements of the returned array must equal the respective elements inx.If a broadcasted element in
minis greater than a corresponding broadcasted element inmax, behavior is unspecified and thus implementation-dependent.For scalar
minand/ormax, the scalar values should follow type promotion rules for operations involving arrays and scalar operands (see type-promotion).If
xhas an integral data type and a broadcasted element inminormaxis outside the bounds of the data type ofx, behavior is unspecified and thus implementation-dependent.If either
minormaxis an array having a different data type thanx, behavior is unspecified and thus implementation-dependent.
Special cases
If
x_iisNaN, the result isNaN.If
min_iisNaN, the result isNaN.If
max_iisNaN, the result isNaN.
Added in version 2023.12.
Changed in version 2024.12: Added special case behavior when one of the operands is
NaN.Changed in version 2024.12: Clarified that behavior is only defined when
x,min, andmaxresolve to arrays having the same data type.Changed in version 2024.12: Clarified that behavior is only defined when elements of
minandmaxare inside the bounds of the input array data type.
- complex128: TDtype¶
- complex64: TDtype¶
- concat: concat[TArray]¶
Joins a sequence of arrays along an existing axis.
- Parameters:
arrays (Union[Tuple[array, ...], List[array]]) – input arrays to join. The arrays must have the same shape, except in the dimension specified by
axis.axis (Optional[int]) – axis along which to join the arrays. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes in each array. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. IfaxisisNone, arrays must be flattened before concatenation. Default:0.
- Returns:
out – an output array containing the concatenated values. If the input arrays have different data types, normal type-promotion must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays.
Note
This specification leaves type promotion between data type families (i.e.,
intxxandfloatxx) unspecified and thus implementation-defined.- Return type:
array
- conj: conj[TArray]¶
Returns the complex conjugate for each element
x_iof the input arrayx.For complex numbers of the form
\[a + bj\]the complex conjugate is defined as
\[a - bj\]Hence, the returned complex conjugates must be computed by negating the imaginary component of each element
x_i.- Parameters:
x (array) – input array. Must have a numeric data type.
- Returns:
out – an array containing the element-wise results. The returned array must have the same data type as
x.- Return type:
array
Notes
Whether the returned array and the input array share the same underlying memory is unspecified and thus implementation-defined.
Added in version 2022.12.
Changed in version 2024.12: Added support for real-valued arrays.
- copysign: copysign[TArray]¶
Composes a floating-point value with the magnitude of
x1_iand the sign ofx2_ifor each element of the input arrayx1.- Parameters:
x1 (Union[array, int, float]) – input array containing magnitudes. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – input array whose sign bits are applied to the magnitudes of
x1. Must be compatible withx1(see broadcasting). Should have a real-valued floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For real-valued floating-point operands, let
|x|be the absolute value, and ifx1_iis notNaN,If
x2_iis less than0, the result is-|x1_i|.If
x2_iis-0, the result is-|x1_i|.If
x2_iis+0, the result is|x1_i|.If
x2_iis greater than0, the result is|x1_i|.If
x2_iisNaNand the sign bit ofx2_iis1, the result is-|x1_i|.If
x2_iisNaNand the sign bit ofx2_iis0, the result is|x1_i|.If
x1_iisNaNandx2_iis less than0, the result isNaNwith a sign bit of1.If
x1_iisNaNandx2_iis-0, the result isNaNwith a sign bit of1.If
x1_iisNaNandx2_iis+0, the result isNaNwith a sign bit of0.If
x1_iisNaNandx2_iis greater than0, the result isNaNwith a sign bit of0.If
x1_iisNaNandx2_iisNaNand the sign bit ofx2_iis1, the result isNaNwith a sign bit of1.If
x1_iisNaNandx2_iisNaNand the sign bit ofx2_iis0, the result isNaNwith a sign bit of0.
Added in version 2023.12.
Changed in version 2024.12: Added scalar argument support.
- cos: cos[TArray]¶
Calculates an implementation-dependent approximation to the cosine for each element
x_iof the input arrayx.Each element
x_iis assumed to be expressed in radians.Note
The cosine is an entire function on the complex plane and has no branch cuts.
Note
For complex arguments, the mathematical definition of cosine is
\[\begin{split}\begin{align} \operatorname{cos}(x) &= \sum_{n=0}^\infty \frac{(-1)^n}{(2n)!} x^{2n} \\ &= \frac{e^{jx} + e^{-jx}}{2} \\ &= \operatorname{cosh}(jx) \end{align}\end{split}\]where \(\operatorname{cosh}\) is the hyperbolic cosine.
- Parameters:
x (array) – input array whose elements are each expressed in radians. Should have a floating-point data type.
- Returns:
out – an array containing the cosine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is1.If
x_iis-0, the result is1.If
x_iis+infinity, the result isNaN.If
x_iis-infinity, the result isNaN.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
cosh(x*1j).Changed in version 2022.12: Added complex data type support.
- cosh: cosh[TArray]¶
Calculates an implementation-dependent approximation to the hyperbolic cosine for each element
x_iin the input arrayx.The mathematical definition of the hyperbolic cosine is
\[\operatorname{cosh}(x) = \frac{e^x + e^{-x}}{2}\]Note
The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period \(2\pi j\), with respect to the imaginary component.
- Parameters:
x (array) – input array whose elements each represent a hyperbolic angle. Should have a floating-point data type.
- Returns:
out – an array containing the hyperbolic cosine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
Note
For all operands,
cosh(x)must equalcosh(-x).For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is1.If
x_iis-0, the result is1.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andNote
For complex floating-point operands,
cosh(conj(x))must equalconj(cosh(x)).If
ais+0andbis+0, the result is1 + 0j.If
ais+0andbis+infinity, the result isNaN + 0j(sign of the imaginary component is unspecified).If
ais+0andbisNaN, the result isNaN + 0j(sign of the imaginary component is unspecified).If
ais a nonzero finite number andbis+infinity, the result isNaN + NaN j.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis+0, the result is+infinity + 0j.If
ais+infinityandbis a nonzero finite number, the result is+infinity * cis(b).If
ais+infinityandbis+infinity, the result is+infinity + NaN j(sign of the real component is unspecified).If
ais+infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis either+0or-0, the result isNaN + 0j(sign of the imaginary component is unspecified).If
aisNaNandbis a nonzero finite number, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
where
cis(v)iscos(v) + sin(v)*1j.Changed in version 2022.12: Added complex data type support.
- count_nonzero: count_nonzero[TArray]¶
Counts the number of array elements which are non-zero.
- Parameters:
x (array) – input array.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to count non-zero values. By default, the number of non-zero values must be computed over the entire array. If a tuple of integers, the number of non-zero values must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if the number of non-zeros values was computed over the entire array, a zero-dimensional array containing the total number of non-zero values; otherwise, a non-zero-dimensional array containing the counts along the specified axes. The returned array must have the default array index data type.
- Return type:
array
Notes
If
xhas a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero.If
xhas a boolean data type, non-zero elements are those elements which are equal toTrue.
Added in version 2024.12.
- cumulative_prod: cumulative_prod[TArray, TDtype]¶
Calculates the cumulative product of elements in the input array
x.- Parameters:
x (array) – input array. Should have one or more dimensions (axes). Should have a numeric data type.
axis (Optional[int]) –
axis along which to compute the cumulative product. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.If
xis a one-dimensional array, providing anaxismust be optional; however, ifxhas more than one dimension, providing anaxismust be required.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the product (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.include_initial (bool) – boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the multiplicative identity (i.e., one). Default:
False.
- Returns:
out – an array containing the cumulative products. The returned array must have a data type as described by the
dtypeparameter above.Let
Mbe the size of the axis along which to compute the cumulative product. The returned array must have a shape determined according to the following rules:if
include_initialisTrue, the returned array must have the same shape asx, except the size of the axis along which to compute the cumulative product must beM+1.if
include_initialisFalse, the returned array must have the same shape asx.
- Return type:
array
Notes
When
xis a zero-dimensional array, behavior is unspecified and thus implementation-defined.
Special Cases
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
multiply().Added in version 2024.12.
- cumulative_sum: cumulative_sum[TArray, TDtype]¶
Calculates the cumulative sum of elements in the input array
x.- Parameters:
x (array) – input array. Should have one or more dimensions (axes). Should have a numeric data type.
axis (Optional[int]) –
axis along which to compute the cumulative sum. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.If
xis a one-dimensional array, providing anaxismust be optional; however, ifxhas more than one dimension, providing anaxismust be required.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the sum (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.include_initial (bool) – boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the additive identity (i.e., zero). Default:
False.
- Returns:
out – an array containing the cumulative sums. The returned array must have a data type as described by the
dtypeparameter above.Let
Mbe the size of the axis along which to compute the cumulative sum. The returned array must have a shape determined according to the following rules:if
include_initialisTrue, the returned array must have the same shape asx, except the size of the axis along which to compute the cumulative sum must beM+1.if
include_initialisFalse, the returned array must have the same shape asx.
- Return type:
array
Notes
When
xis a zero-dimensional array, behavior is unspecified and thus implementation-defined.
Special Cases
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
add().Added in version 2023.12.
Changed in version 2024.12: Behavior when providing a zero-dimensional array is explicitly left unspecified.
- diff: diff[TArray]¶
Calculates the n-th discrete forward difference along a specified axis.
- Parameters:
x (array) – input array. Should have a numeric data type.
axis (int) – axis along which to compute differences. A valid
axismust be an integer on the interval[-N, N), whereNis the number of axes inx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute differences by counting backward from the last axis (where-1refers to the last axis). If provided an invalidaxis, the function must raise an exception. Default:-1.n (int) – number of times to recursively compute differences. Default:
1.prepend (Optional[array]) – values to prepend to a specified axis prior to computing differences. Must have the same shape as
x, except for the axis specified byaxiswhich can have any size. Should have the same data type asx. Default:None.append (Optional[array]) – values to append to a specified axis prior to computing differences. Must have the same shape as
x, except for the axis specified byaxiswhich can have any size. Should have the same data type asx. Default:None.
- Returns:
out – an array containing the n-th differences. Should have the same data type as
x. Must have the same shape asx, except for the axis specified byaxiswhich must have a size determined as follows:Let
Mbe the number of elements along an axis specified byaxis.Let
N1be the number of prepended values along an axis specified byaxis.Let
N2be the number of appended values along an axis specified byaxis.The final size of the axis specified by
axismust beM + N1 + N2 - n.
- Return type:
array
Notes
The first-order differences are given by
out[i] = x[i+1] - x[i]along a specified axis. Higher-order differences must be calculated recursively (e.g., by callingdiff(out, axis=axis, n=n-1)).If a conforming implementation chooses to support
prependandappendarrays which have a different data type thanx, behavior is unspecified and thus implementation-defined. Implementations may choose to type promote (type-promotion), castprependand/orappendto the same data type asx, or raise an exception.
Added in version 2024.12.
- divide: divide[TArray]¶
Calculates the division of each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float, complex]) – dividend input array. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – divisor input array. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.If one or both of the input arrays have integer data types, the result is implementation-dependent, as type promotion between data type “kinds” (e.g., integer versus floating-point) is unspecified.
Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type.
Special cases
For real-valued floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis either+infinityor-infinityandx2_iis either+infinityor-infinity, the result isNaN.If
x1_iis either+0or-0andx2_iis either+0or-0, the result isNaN.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis-0andx2_iis greater than0, the result is-0.If
x1_iis+0andx2_iis less than0, the result is-0.If
x1_iis-0andx2_iis less than0, the result is+0.If
x1_iis greater than0andx2_iis+0, the result is+infinity.If
x1_iis greater than0andx2_iis-0, the result is-infinity.If
x1_iis less than0andx2_iis+0, the result is-infinity.If
x1_iis less than0andx2_iis-0, the result is+infinity.If
x1_iis+infinityandx2_iis a positive (i.e., greater than0) finite number, the result is+infinity.If
x1_iis+infinityandx2_iis a negative (i.e., less than0) finite number, the result is-infinity.If
x1_iis-infinityandx2_iis a positive (i.e., greater than0) finite number, the result is-infinity.If
x1_iis-infinityandx2_iis a negative (i.e., less than0) finite number, the result is+infinity.If
x1_iis a positive (i.e., greater than0) finite number andx2_iis+infinity, the result is+0.If
x1_iis a positive (i.e., greater than0) finite number andx2_iis-infinity, the result is-0.If
x1_iis a negative (i.e., less than0) finite number andx2_iis+infinity, the result is-0.If
x1_iis a negative (i.e., less than0) finite number andx2_iis-infinity, the result is+0.If
x1_iandx2_ihave the same mathematical sign and are both nonzero finite numbers, the result has a positive mathematical sign.If
x1_iandx2_ihave different mathematical signs and are both nonzero finite numbers, the result has a negative mathematical sign.In the remaining cases, where neither
-infinity,+0,-0, norNaNis involved, the quotient must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported rounding mode. If the magnitude is too large to represent, the operation overflows and the result is aninfinityof appropriate mathematical sign. If the magnitude is too small to represent, the operation underflows and the result is a zero of appropriate mathematical sign.
For complex floating-point operands, division is defined according to the following table. For real components
aandcand imaginary componentsbandd,c
dj
c + dj
a
a / c
-(a/d)j
special rules
bj
(b/c)j
b/d
special rules
a + bj
(a/c) + (b/c)j
b/d - (a/d)j
special rules
In general, for complex floating-point operands, real-valued floating-point special cases must independently apply to the real and imaginary component operations involving real numbers as described in the above table.
When
a,b,c, ordare all finite numbers (i.e., a value other thanNaN,+infinity, or-infinity), division of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number division\[\frac{a + bj}{c + dj} = \frac{(ac + bd) + (bc - ad)j}{c^2 + d^2}\]When at least one of
a,b,c, ordisNaN,+infinity, or-infinity,If
a,b,c, anddare allNaN, the result isNaN + NaN j.In the remaining cases, the result is implementation dependent.
Note
For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is
NaN, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations.Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- e: TArray¶
IEEE 754 floating-point representation of Euler’s constant.
e = 2.71828182845904523536028747135266249775724709369995...
- empty: empty[TArray, TDtype, TDevice]¶
Returns an uninitialized array having a specified shape.
- Parameters:
shape (Union[int, Tuple[int, ...]]) – output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array containing uninitialized data.
- Return type:
array
- empty_like: empty_like[TArray, TDtype, TDevice]¶
Returns an uninitialized array with the same
shapeas an input arrayx.- Parameters:
x (array) – input array from which to derive the output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be inferred fromx. Default:None.device (Optional[device]) – device on which to place the created array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the same shape as
xand containing uninitialized data.- Return type:
array
- equal: equal[TArray]¶
Computes the truth value of
x1_i == x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special Cases
For real-valued floating-point operands,
If
x1_iisNaNorx2_iisNaN, the result isFalse.If
x1_iis+infinityandx2_iis+infinity, the result isTrue.If
x1_iis-infinityandx2_iis-infinity, the result isTrue.If
x1_iis-0andx2_iis either+0or-0, the result isTrue.If
x1_iis+0andx2_iis either+0or-0, the result isTrue.If
x1_iis a finite number,x2_iis a finite number, andx1_iequalsx2_i, the result isTrue.In the remaining cases, the result is
False.
For complex floating-point operands, let
a = real(x1_i),b = imag(x1_i),c = real(x2_i),d = imag(x2_i), andIf
a,b,c, ordisNaN, the result isFalse.In the remaining cases, the result is the logical AND of the equality comparison between the real values
aandc(real components) and between the real valuesbandd(imaginary components), as described above for real-valued floating-point operands (i.e.,a == c AND b == d).
Note
For discussion of complex number equality, see complex-numbers.
Note
Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- exp: exp[TArray]¶
Calculates an implementation-dependent approximation to the exponential function for each element
x_iof the input arrayx(eraised to the power ofx_i, whereeis the base of the natural logarithm).Note
For complex floating-point operands,
exp(conj(x))must equalconj(exp(x)).Note
The exponential function is an entire function in the complex plane and has no branch cuts.
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated exponential function result for each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is1.If
x_iis-0, the result is1.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is+0.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result is1 + 0j.If
ais a finite number andbis+infinity, the result isNaN + NaN j.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis+0, the result isinfinity + 0j.If
ais-infinityandbis a finite number, the result is+0 * cis(b).If
ais+infinityandbis a nonzero finite number, the result is+infinity * cis(b).If
ais-infinityandbis+infinity, the result is0 + 0j(signs of real and imaginary components are unspecified).If
ais+infinityandbis+infinity, the result isinfinity + NaN j(sign of real component is unspecified).If
ais-infinityandbisNaN, the result is0 + 0j(signs of real and imaginary components are unspecified).If
ais+infinityandbisNaN, the result isinfinity + NaN j(sign of real component is unspecified).If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis not equal to0, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
where
cis(v)iscos(v) + sin(v)*1j.Changed in version 2022.12: Added complex data type support.
- expand_dims: expand_dims[TArray]¶
Expands the shape of an array by inserting a new axis of size one at the position (or positions) specified by
axis.- Parameters:
x (array) – input array.
axis (Union[int, Tuple[int, ...]]) –
axis position(s) (zero-based). If
axisis an integer,axismust be equivalent to the tuple(axis,). Ifaxisis a tuple,a valid axis position must reside on the half-open interval
[-M, M), whereM = N + len(axis)andNis the number of dimensions inx.if the i-th entry is a negative integer, the axis position of the inserted singleton dimension in the output array must be computed as
M + axis[i].each entry of
axismust resolve to a unique positive axis position.for each entry of
axis, the corresponding dimension in the expanded output array must be a singleton dimension.for the remaining dimensions of the expanded output array, the output array dimensions must correspond to the dimensions of
xin order.if provided an invalid axis position, the function must raise an exception.
- Returns:
out – an expanded output array. Must have the same data type as
x. Ifaxisis an integer, the output array must haveN + 1dimensions. Ifaxisis a tuple, the output array must haveN + len(axis)dimensions.- Return type:
array
- Raises:
IndexError – If provided an invalid
axis, anIndexErrorshould be raised.
Notes
Calling this function with a tuple of axis positions must be semantically equivalent to calling this function repeatedly with a single axis position only when the following three conditions are met:
each entry of the tuple is normalized to positive axis positions according to the number of dimensions in the expanded output array.
the normalized positive axis positions are sorted in ascending order.
the normalized positive axis positions are unique.
Changed in version 2025.12: Added support for specifying a tuple of axis positions.
- expm1: expm1[TArray]¶
Calculates an implementation-dependent approximation to
exp(x)-1for each elementx_iof the input arrayx.Note
The purpose of this function is to calculate
exp(x)-1.0more accurately when x is close to zero. Accordingly, conforming implementations should avoid implementing this function as simplyexp(x)-1.0. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation.Note
For complex floating-point operands,
expm1(conj(x))must equalconj(expm1(x)).Note
The exponential function is an entire function in the complex plane and has no branch cuts.
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-1.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result is0 + 0j.If
ais a finite number andbis+infinity, the result isNaN + NaN j.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis+0, the result is+infinity + 0j.If
ais-infinityandbis a finite number, the result is+0 * cis(b) - 1.0.If
ais+infinityandbis a nonzero finite number, the result is+infinity * cis(b) - 1.0.If
ais-infinityandbis+infinity, the result is-1 + 0j(sign of imaginary component is unspecified).If
ais+infinityandbis+infinity, the result isinfinity + NaN j(sign of real component is unspecified).If
ais-infinityandbisNaN, the result is-1 + 0j(sign of imaginary component is unspecified).If
ais+infinityandbisNaN, the result isinfinity + NaN j(sign of real component is unspecified).If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis not equal to0, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
where
cis(v)iscos(v) + sin(v)*1j.Changed in version 2022.12: Added complex data type support.
- eye: eye[TArray, TDtype, TDevice]¶
Returns a two-dimensional array with ones on the
kth diagonal and zeros elsewhere.Note
An output array having a complex floating-point data type must have the value
1 + 0jalong thekth diagonal and0 + 0jelsewhere.- Parameters:
n_rows (int) – number of rows in the output array.
n_cols (Optional[int]) – number of columns in the output array. If
None, the default number of columns in the output array is equal ton_rows. Default:None.k (int) – index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and
0to the main diagonal. Default:0.dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array where all elements are equal to zero, except for the
kth diagonal, whose values are equal to one.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- finfo: finfo[TArray, TDtype]¶
Machine limits for floating-point data types.
- Parameters:
type (Union[dtype, array]) –
the kind of floating-point data-type about which to get information. If complex, the information is about its component data type.
Note
Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component.
- Returns:
out – an object having the following attributes:
bits: int
number of bits occupied by the real-valued floating-point data type.
eps: float
difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard.
max: float
largest representable real-valued number.
min: float
smallest representable real-valued number.
smallest_normal: float
smallest positive real-valued floating-point number with full precision.
dtype: dtype
real-valued floating-point data type.
Added in version 2022.12.
- Return type:
finfo object
Notes
Changed in version 2022.12: Added complex data type support.
- flip: flip[TArray]¶
Reverses the order of elements in an array along the given axis.
- Parameters:
x (array) – input array.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis (or axes) along which to reverse elements. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. IfaxisisNone, the function must flip all input array axes. If provided more than one axis, the function must flip only the specified axes. Default:None.
- Returns:
out – an output array. The returned array must have the same data type and shape as
x. The returned array must have the same elements asx, but which are reordered relative tox.- Return type:
array
- float32: TDtype¶
- float64: TDtype¶
- floor: floor[TArray]¶
Rounds each element
x_iof the input arrayxto the greatest (i.e., closest to+infinity) integer-valued number that is not greater thanx_i.- Parameters:
x (array) – input array. Should have a real-valued data type.
- Returns:
out – an array containing the rounded result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
If
x_iis already integer-valued, the result isx_i.
For floating-point operands,
If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iisNaN, the result isNaN.
- floor_divide: floor_divide[TArray]¶
Rounds the result of dividing each element
x1_iof the input arrayx1by the respective elementx2_iof the input arrayx2to the greatest (i.e., closest to +infinity) integer-value number that is not greater than the division result.- Parameters:
x1 (Union[array, int, float]) – dividend input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – divisor input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined.
Special cases
Note
Floor division was introduced in Python via PEP 238 with the goal to disambiguate “true division” (i.e., computing an approximation to the mathematical operation of division) from “floor division” (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a
float, while the latter was computed when both operands wereints. Overloading the/operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected.To resolve this ambiguity,
/was designated for true division, and//was designated for floor division. Semantically, floor division was defined as equivalent toa // b == floor(a/b); however, special floating-point cases were left ill-defined.Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is
infinity, libraries may diverge with some choosing to strictly followfloor(a/b)and others choosing to pair//with%according to the relationb = a % b + b * (a // b). The special cases leading to divergent behavior are documented below.This specification prefers floor division to match
floor(divide(x1, x2))in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior.For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis either+infinityor-infinityandx2_iis either+infinityor-infinity, the result isNaN.If
x1_iis either+0or-0andx2_iis either+0or-0, the result isNaN.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis-0andx2_iis greater than0, the result is-0.If
x1_iis+0andx2_iis less than0, the result is-0.If
x1_iis-0andx2_iis less than0, the result is+0.If
x1_iis greater than0andx2_iis+0, the result is+infinity.If
x1_iis greater than0andx2_iis-0, the result is-infinity.If
x1_iis less than0andx2_iis+0, the result is-infinity.If
x1_iis less than0andx2_iis-0, the result is+infinity.If
x1_iis+infinityandx2_iis a positive (i.e., greater than0) finite number, the result is+infinity. (note: libraries may returnNaNto match Python behavior.)If
x1_iis+infinityandx2_iis a negative (i.e., less than0) finite number, the result is-infinity. (note: libraries may returnNaNto match Python behavior.)If
x1_iis-infinityandx2_iis a positive (i.e., greater than0) finite number, the result is-infinity. (note: libraries may returnNaNto match Python behavior.)If
x1_iis-infinityandx2_iis a negative (i.e., less than0) finite number, the result is+infinity. (note: libraries may returnNaNto match Python behavior.)If
x1_iis a positive (i.e., greater than0) finite number andx2_iis+infinity, the result is+0.If
x1_iis a positive (i.e., greater than0) finite number andx2_iis-infinity, the result is-0. (note: libraries may return-1.0to match Python behavior.)If
x1_iis a negative (i.e., less than0) finite number andx2_iis+infinity, the result is-0. (note: libraries may return-1.0to match Python behavior.)If
x1_iis a negative (i.e., less than0) finite number andx2_iis-infinity, the result is+0.If
x1_iandx2_ihave the same mathematical sign and are both nonzero finite numbers, the result has a positive mathematical sign.If
x1_iandx2_ihave different mathematical signs and are both nonzero finite numbers, the result has a negative mathematical sign.In the remaining cases, where neither
-infinity,+0,-0, norNaNis involved, the quotient must be computed and rounded to the greatest (i.e., closest to +infinity) representable integer-value number that is not greater than the division result. If the magnitude is too large to represent, the operation overflows and the result is aninfinityof appropriate mathematical sign. If the magnitude is too small to represent, the operation underflows and the result is a zero of appropriate mathematical sign.
Changed in version 2024.12: Added scalar argument support.
- from_dlpack: from_dlpack[TArray, TDevice]¶
Returns a new array containing the data from another (array) object with a
__dlpack__method.- Parameters:
x (object) – input (array) object.
device (Optional[device]) –
device on which to place the created array. If
deviceisNoneandxsupports DLPack, the output array must be on the same device asx. Default:None.The v2023.12 standard only mandates that a compliant library should offer a way for
from_dlpackto return an array whose underlying memory is accessible to the Python interpreter, when the correspondingdeviceis provided. If the array library does not support such cases at all, the function must raiseBufferError. If a copy must be made to enable this support butcopyis set toFalse, the function must raiseValueError.Other device kinds will be considered for standardization in a future version of this API standard.
copy (Optional[bool]) – boolean indicating whether or not to copy the input. If
True, the function must always copy. IfFalse, the function must never copy, and raiseBufferErrorin case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). IfNone, the function must reuse the existing memory buffer if possible and copy otherwise. Default:None.
- Returns:
out – an array containing the data in
x.Note
The returned array may be either a copy or a view. See data-interchange for details.
- Return type:
array
- Raises:
BufferError – The
__dlpack__and__dlpack_device__methods on the input array may raiseBufferErrorwhen the data cannot be exported as DLPack (e.g., incompatible dtype, strides, or device). It may also raise other errors when export fails for other reasons (e.g., not enough memory available to materialize the data).from_dlpackmust propagate such exceptions.AttributeError – If the
__dlpack__and__dlpack_device__methods are not present on the input array. This may happen for libraries that are never able to export their data with DLPack.ValueError – If data exchange is possible via an explicit copy but
copyis set toFalse.
Notes
See
array.__dlpack__()for implementation suggestions for from_dlpack in order to handle DLPack versioning correctly.A way to move data from two array libraries to the same device (assumed supported by both libraries) in a library-agnostic fashion is illustrated below:
def func(x, y): xp_x = x.__array_namespace__() xp_y = y.__array_namespace__() # Other functions than `from_dlpack` only work if both arrays are from the same library. So if # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: if not xp_x == xp_y: y = xp_x.from_dlpack(y, copy=True, device=x.device) # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` ...
Changed in version 2023.12: Required exceptions to address unsupported use cases.
Changed in version 2023.12: Added device and copy support.
- full: full[TArray, TDtype, TDevice]¶
Returns a new array having a specified
shapeand filled withfill_value.- Parameters:
shape (Union[int, Tuple[int, ...]]) – output array shape.
fill_value (Union[bool, int, float, complex]) – fill value.
dtype (Optional[dtype]) –
output array data type. If
dtypeisNone, the output array data type must be inferred fromfill_valueaccording to the following rules:If the fill value is an
int, the output array data type must be the default integer data type.If the fill value is a
float, the output array data type must be the default real-valued floating-point data type.If the fill value is a
complexnumber, the output array data type must be the default complex floating-point data type.If the fill value is a
bool, the output array must have a boolean data type. Default:None.
Note
If the
fill_valueexceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array where every element is equal to
fill_value.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- full_like: full_like[TArray, TDtype, TDevice]¶
Returns a new array filled with
fill_valueand having the sameshapeas an input arrayx.- Parameters:
x (array) – input array from which to derive the output array shape.
fill_value (Union[bool, int, float, complex]) – fill value.
dtype (Optional[dtype]) –
output array data type. If
dtypeisNone, the output array data type must be inferred fromx. Default:None.Note
If the
fill_valueexceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined.Note
If the
fill_valuehas a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see type-promotion), behavior is unspecified and, thus, implementation-defined.device (Optional[device]) – device on which to place the created array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the same shape as
xand where every element is equal tofill_value.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- greater: greater[TArray]¶
Computes the truth value of
x1_i > x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- greater_equal: greater_equal[TArray]¶
Computes the truth value of
x1_i >= x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- hypot: hypot[TArray]¶
Computes the square root of the sum of squares for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
The value computed by this function may be interpreted as the length of the hypotenuse of a right-angled triangle with sides of length
x1_iandx2_i, the distance of a point(x1_i, x2_i)from the origin(0, 0), or the magnitude of a complex numberx1_i + x2_i * 1j.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.The purpose of this function is to avoid underflow and overflow during intermediate stages of computation. Accordingly, conforming implementations should not use naive implementations.
Special Cases
For real-valued floating-point operands,
If
x1_iis+infinityor-infinityandx2_iis any value, includingNaN, the result is+infinity.If
x2_iis+infinityor-infinityandx1_iis any value, includingNaN, the result is+infinity.If
x1_iis either+0or-0, the result is equivalent toabs(x2_i).If
x2_iis either+0or-0, the result is equivalent toabs(x1_i).If
x1_iis a finite number orNaNandx2_iisNaN, the result isNaN.If
x2_iis a finite number orNaNandx1_iisNaN, the result isNaN.Underflow may only occur when both arguments are subnormal and the correct result is also subnormal.
For real-valued floating-point operands,
hypot(x1, x2)must equalhypot(x2, x1),hypot(x1, -x2),hypot(-x1, x2), andhypot(-x1, -x2).Note
IEEE 754-2019 requires support for subnormal (a.k.a., denormal) numbers, which are useful for supporting gradual underflow. However, hardware support for subnormal numbers is not universal, and many platforms (e.g., accelerators) and compilers support toggling denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) behavior to increase performance and to guard against timing attacks.
Accordingly, conforming implementations may vary in their support for subnormal numbers.
Added in version 2023.12.
Changed in version 2024.12: Added scalar argument support.
- iinfo: iinfo[TArray, TDtype]¶
Machine limits for integer data types.
- Parameters:
type (Union[dtype, array]) – the kind of integer data-type about which to get information.
- Returns:
out – an object having the following attributes:
bits: int
number of bits occupied by the type.
max: int
largest representable number.
min: int
smallest representable number.
dtype: dtype
integer data type.
Added in version 2022.12.
- Return type:
iinfo object
- imag: imag[TArray]¶
Returns the imaginary component of a complex number for each element
x_iof the input arrayx.- Parameters:
x (array) – input array. Should have a complex floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as
x(e.g., ifxiscomplex64, the returned array must have the floating-point data typefloat32).- Return type:
array
Notes
Added in version 2022.12.
- inf: TArray¶
IEEE 754 floating-point representation of (positive) infinity.
- int16: TDtype¶
- int32: TDtype¶
- int64: TDtype¶
- int8: TDtype¶
- isdtype: isdtype[TDtype]¶
Returns a boolean indicating whether a provided dtype is of a specified data type “kind”.
- Parameters:
dtype (dtype) – the input dtype.
kind (Union[str, dtype, Tuple[Union[str, dtype], ...]]) –
data type kind.
If
kindis a dtype, the function must return a boolean indicating whether the inputdtypeis equal to the dtype specified bykind.If
kindis a string, the function must return a boolean indicating whether the inputdtypeis of a specified data type kind. The following dtype kinds must be supported:'bool': boolean data types (e.g.,bool).'signed integer': signed integer data types (e.g.,int8,int16,int32,int64).'unsigned integer': unsigned integer data types (e.g.,uint8,uint16,uint32,uint64).'integral': integer data types. Shorthand for('signed integer', 'unsigned integer').'real floating': real-valued floating-point data types (e.g.,float32,float64).'complex floating': complex floating-point data types (e.g.,complex64,complex128).'numeric': numeric data types. Shorthand for('integral', 'real floating', 'complex floating').
If
kindis a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the inputdtypeis either equal to a specified dtype or belongs to at least one specified data type kind.
Note
A conforming implementation of the array API standard is not limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting
float16andbfloat16can includefloat16andbfloat16in thereal floatingdata type kind. Similarly, implementations supportingint128can includeint128in thesigned integerdata type kind.In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation.
- Returns:
out – boolean indicating whether a provided dtype is of a specified data type kind.
- Return type:
Notes
Added in version 2022.12.
- isfinite: isfinite[TArray]¶
Tests each element
x_iof the input arrayxto determine if finite.- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing test results. The returned array must have a data type of
bool.- Return type:
array
Notes
Special Cases
For real-valued floating-point operands,
If
x_iis either+infinityor-infinity, the result isFalse.If
x_iisNaN, the result isFalse.If
x_iis a finite number, the result isTrue.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
aisNaNorbisNaN, the result isFalse.If
ais either+infinityor-infinityandbis any value, the result isFalse.If
ais any value andbis either+infinityor-infinity, the result isFalse.If
ais a finite number andbis a finite number, the result isTrue.
Changed in version 2022.12: Added complex data type support.
- isin: isin[TArray]¶
Tests for each element in
x1whether the element is inx2.- Parameters:
x1 (Union[array, int]) – first input array. Should have an integer data type.
x2 (Union[array, int]) – second input array. Should have an integer data type.
invert (bool) – boolean indicating whether to invert the test criterion. If
True, the function must test whether each element inx1is not inx2. IfFalse, the function must test whether each element inx1is inx2. Default:False.
- Returns:
out – an array containing element-wise test results. The returned array must have a boolean data type. If
x1is an array, the returned array must have the same shape asx1; otherwise, the returned array must be a zero-dimensional array containing the result.- Return type:
array
Notes
At least one of
x1orx2must be an array.If an element in
x1is inx2, the corresponding element in the output array must beTrue; otherwise, the corresponding element in the output array must beFalse.Testing whether an element in
x1corresponds to an element inx2must be determined based on value equality (seeequal()).Comparison of arrays without a corresponding promotable data type (see type-promotion) is unspecified and thus implementation-defined.
- isinf: isinf[TArray]¶
Tests each element
x_iof the input arrayxto determine if equal to positive or negative infinity.- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing test results. The returned array must have a data type of
bool.- Return type:
array
Notes
Special Cases
For real-valued floating-point operands,
If
x_iis either+infinityor-infinity, the result isTrue.In the remaining cases, the result is
False.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+infinityor-infinityandbis any value (includingNaN), the result isTrue.If
ais either a finite number orNaNandbis either+infinityor-infinity, the result isTrue.In the remaining cases, the result is
False.
Changed in version 2022.12: Added complex data type support.
- isnan: isnan[TArray]¶
Tests each element
x_iof the input arrayxto determine whether the element isNaN.- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing test results. The returned array should have a data type of
bool.- Return type:
array
Notes
Special Cases
For real-valued floating-point operands,
If
x_iisNaN, the result isTrue.In the remaining cases, the result is
False.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
aorbisNaN, the result isTrue.In the remaining cases, the result is
False.
Changed in version 2022.12: Added complex data type support.
- less: less[TArray]¶
Computes the truth value of
x1_i < x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- less_equal: less_equal[TArray]¶
Computes the truth value of
x1_i <= x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- linspace: linspace[TArray, TDtype, TDevice]¶
Returns evenly spaced numbers over a specified interval.
Let \(N\) be the number of generated values (which is either
numornum+1depending on whetherendpointisTrueorFalse, respectively). For real-valued output arrays, the spacing between values is given by\[\Delta_{\textrm{real}} = \frac{\textrm{stop} - \textrm{start}}{N - 1}\]For complex output arrays, let
a = real(start),b = imag(start),c = real(stop), andd = imag(stop). The spacing between complex values is given by\[\Delta_{\textrm{complex}} = \frac{c-a}{N-1} + \frac{d-b}{N-1} j\]- Parameters:
start (Union[int, float, complex]) – the start of the interval.
stop (Union[int, float, complex]) –
the end of the interval. If
endpointisFalse, the function must generate a sequence ofnum+1evenly spaced numbers starting withstartand ending withstopand exclude thestopfrom the returned array such that the returned array consists of evenly spaced numbers over the half-open interval[start, stop). IfendpointisTrue, the output array must consist of evenly spaced numbers over the closed interval[start, stop]. Default:True.Note
The step size changes when endpoint is False.
num (int) – number of samples. Must be a nonnegative integer value.
dtype (Optional[dtype]) –
output array data type. Should be a floating-point data type. If
dtypeisNone,if either
startorstopis acomplexnumber, the output data type must be the default complex floating-point data type.if both
startandstopare real-valued, the output data type must be the default real-valued floating-point data type.
Default:
None.Note
If
dtypeis notNone, conversion ofstartandstopshould obey type-promotion rules. Conversions not specified according to type-promotion rules may or may not be permitted by a conforming array library.device (Optional[device]) – device on which to place the created array. Default:
None.endpoint (bool) – boolean indicating whether to include
stopin the interval. Default:True.
- Returns:
out – a one-dimensional array containing evenly spaced values.
- Return type:
array
Notes
Note
While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable.
Note
As mixed data type promotion is implementation-defined, behavior when
startorstopexceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception.Changed in version 2022.12: Added complex data type support.
- log: log[TArray]¶
Calculates an implementation-dependent approximation to the natural (base
e) logarithm for each elementx_iof the input arrayx.Note
The natural logarithm of a complex number \(z\) with polar coordinates \((r,\theta)\) equals \(\ln r + (\theta + 2n\pi)j\) with principal value \(\ln r + \theta j\).
Note
For complex floating-point operands,
log(conj(x))must equalconj(log(x)).Note
By convention, the branch cut of the natural logarithm is the negative real axis \((-\infty, 0)\).
The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component.
Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval \([-\pi j, +\pi j]\) along the imaginary axis and mathematically unbounded along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated natural logarithm for each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than0, the result isNaN.If
x_iis either+0or-0, the result is-infinity.If
x_iis1, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais-0andbis+0, the result is-infinity + πj.If
ais+0andbis+0, the result is-infinity + 0j.If
ais a finite number andbis+infinity, the result is+infinity + πj/2.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais-infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + πj.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0j.If
ais-infinityandbis+infinity, the result is+infinity + 3πj/4.If
ais+infinityandbis+infinity, the result is+infinity + πj/4.If
ais either+infinityor-infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is+infinity + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- log10: log10[TArray]¶
Calculates an implementation-dependent approximation to the base
10logarithm for each elementx_iof the input arrayx.Note
For complex floating-point operands,
log10(conj(x))must equalconj(log10(x)).- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated base
10logarithm for each element inx. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than0, the result isNaN.If
x_iis either+0or-0, the result is-infinity.If
x_iis1, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula
\[\log_{10} x = \frac{\log_{e} x}{\log_{e} 10}\]where \(\log_{e}\) is the natural logarithm, as implemented by
log().Changed in version 2022.12: Added complex data type support.
- log1p: log1p[TArray]¶
Calculates an implementation-dependent approximation to
log(1+x), wherelogrefers to the natural (basee) logarithm, for each elementx_iof the input arrayx.Note
The purpose of this function is to calculate
log(1+x)more accurately when x is close to zero. Accordingly, conforming implementations should avoid implementing this function as simplylog(1+x). See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation.Note
For complex floating-point operands,
log1p(conj(x))must equalconj(log1p(x)).Note
By convention, the branch cut of the natural logarithm is the negative real axis \((-\infty, 0)\).
The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component.
Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval \([-\pi j, +\pi j]\) along the imaginary axis and mathematically unbounded along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than-1, the result isNaN.If
x_iis-1, the result is-infinity.If
x_iis-0, the result is-0.If
x_iis+0, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais-1andbis+0, the result is-infinity + 0j.If
ais a finite number andbis+infinity, the result is+infinity + πj/2.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais-infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + πj.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0j.If
ais-infinityandbis+infinity, the result is+infinity + 3πj/4.If
ais+infinityandbis+infinity, the result is+infinity + πj/4.If
ais either+infinityor-infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is+infinity + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- log2: log2[TArray]¶
Calculates an implementation-dependent approximation to the base
2logarithm for each elementx_iof the input arrayx.Note
For complex floating-point operands,
log2(conj(x))must equalconj(log2(x)).- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated base
2logarithm for each element inx. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than0, the result isNaN.If
x_iis either+0or-0, the result is-infinity.If
x_iis1, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula
\[\log_{2} x = \frac{\log_{e} x}{\log_{e} 2}\]where \(\log_{e}\) is the natural logarithm, as implemented by
log().Changed in version 2022.12: Added complex data type support.
- logaddexp: logaddexp[TArray]¶
Calculates the logarithm of the sum of exponentiations
log(exp(x1) + exp(x2))for each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis+infinityandx2_iis notNaN, the result is+infinity.If
x1_iis notNaNandx2_iis+infinity, the result is+infinity.
Changed in version 2024.12: Added scalar argument support.
- logical_and: logical_and[TArray]¶
Computes the logical AND for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of
False, while non-zeros must be considered the equivalent ofTrue.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of bool.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- logical_not: logical_not[TArray]¶
Computes the logical NOT for each element
x_iof the input arrayx.Note
While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of
False, while non-zeros must be considered the equivalent ofTrue.- Parameters:
x (array) – input array. Should have a boolean data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
- logical_or: logical_or[TArray]¶
Computes the logical OR for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of
False, while non-zeros must be considered the equivalent ofTrue.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- logical_xor: logical_xor[TArray]¶
Computes the logical XOR for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of
False, while non-zeros must be considered the equivalent ofTrue.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- matmul: matmul[TArray]¶
Computes the matrix product.
- Parameters:
x1 (array) –
first input array. Should have a numeric data type. Must have at least one dimension.
If
x1is a one-dimensional array having shape(M,)andx2has more than one dimension,x1must be promoted to a two-dimensional array by prepending1to its dimensions (i.e., must have shape(1, M)). After matrix multiplication, the prepended dimensions in the returned array must be removed.If
x1has more than one dimension (including after vector-to-matrix promotion),shape(x1)[:-2]must be compatible withshape(x2)[:-2](after vector-to-matrix promotion) (see broadcasting).If
x1has shape(..., M, K), the innermost two dimensions form matrices on which to perform matrix multiplication.
x2 (array) –
second input array. Should have a numeric data type. Must have at least one dimension.
If
x2is one-dimensional array having shape(N,)andx1has more than one dimension,x2must be promoted to a two-dimensional array by appending1to its dimensions (i.e., must have shape(N, 1)). After matrix multiplication, the appended dimensions in the returned array must be removed.If
x2has more than one dimension (including after vector-to-matrix promotion),shape(x2)[:-2]must be compatible withshape(x1)[:-2](after vector-to-matrix promotion) (see broadcasting).If
x2has shape(..., K, N), the innermost two dimensions form matrices on which to perform matrix multiplication.
- Returns:
out – output array.
If both
x1andx2are one-dimensional arrays having shape(N,), the returned array must be a zero-dimensional array and must contain the inner product as its only element.If
x1is a two-dimensional array having shape(M, K)andx2is a two-dimensional array having shape(K, N), the returned array must be a two-dimensional array and must contain the conventional matrix product and having shape(M, N).If
x1is a one-dimensional array having shape(K,)andx2is an array having shape(..., K, N), the returned array must be an array having shape(..., N)(i.e., prepended dimensions during vector-to-matrix promotion must be removed) and must contain the conventional matrix product.If
x1is an array having shape(..., M, K)andx2is a one-dimensional array having shape(K,), the returned array must be an array having shape(..., M)(i.e., appended dimensions during vector-to-matrix promotion must be removed) and must contain the conventional matrix product.If
x1is a two-dimensional array having shape(M, K)andx2is an array having shape(..., K, N), the returned array must be an array having shape(..., M, N)and must contain the conventional matrix product for each stacked matrix.If
x1is an array having shape(..., M, K)andx2is a two-dimensional array having shape(K, N), the returned array must be an array having shape(..., M, N)and must contain the conventional matrix product for each stacked matrix.If either
x1orx2has more than two dimensions, the returned array must be an array having a shape determined by broadcastingshape(x1)[:-2]againstshape(x2)[:-2]and must contain the conventional matrix product for each stacked matrix.
The returned array must have a data type determined by type-promotion.
- Return type:
array
- Raises:
Exception – an exception should be raised in the following circumstances: - if either
x1orx2is a zero-dimensional array. - ifx1is a one-dimensional array having shape(K,),x2is a one-dimensional array having shape(L,), andK != L. - ifx1is a one-dimensional array having shape(K,),x2is an array having shape(..., L, N), andK != L. - ifx1is an array having shape(..., M, K),x2is a one-dimensional array having shape(L,), andK != L. - ifx1is an array having shape(..., M, K),x2is an array having shape(..., L, N), andK != L.
Notes
The
matmulfunction must implement the same semantics as the built-in@operator (see PEP 465).If either
x1orx2has a complex floating-point data type, the function must not complex-conjugate or tranpose either argument. If conjugation and/or transposition is desired, a user can explicitly perform these operations prior to computing the matrix product.
Changed in version 2022.12: Added complex data type support.
- matrix_transpose: matrix_transpose[TArray]¶
Transposes a matrix (or a stack of matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices.- Returns:
out – an array containing the transpose for each matrix. The returned array must have shape
(..., N, M). The returned array must have the same data type asx.- Return type:
array
- max: max[TArray]¶
Calculates the maximum value of the input array
x.- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute maximum values. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the maximum value is computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as
x.- Return type:
array
Notes
When the number of elements over which to compute the maximum value is zero, the maximum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if
xis a floating-point input array, returnNaN), or return the minimum possible value for the input arrayxdata type (e.g., ifxis a floating-point array, return-infinity).The order of signed zeros is unspecified and thus implementation-defined. When choosing between
-0or+0as a maximum value, specification-compliant libraries may choose to return either value.For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see complex-number-ordering).
Special Cases
For floating-point operands,
If
x_iisNaN, the maximum value must beNaN(i.e.,NaNvalues propagate).
Changed in version 2023.12: Clarified that the order of signed zeros is implementation-defined.
- maximum: maximum[TArray]¶
Computes the maximum value for each element
x1_iof the input arrayx1relative to the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise maximum values. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.The order of signed zeros is unspecified and thus implementation-defined. When choosing between
-0or+0as a maximum value, specification-compliant libraries may choose to return either value.For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see complex-number-ordering).
Special Cases
For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.
Added in version 2023.12.
Changed in version 2024.12: Added scalar argument support.
- mean: mean[TArray]¶
Calculates the arithmetic mean of the input array
x.- Parameters:
x (array) – input array. Should have a floating-point data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute arithmetic means. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the arithmetic mean is computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as
x.- Return type:
array
Notes
While this specification recommends that this function only accept input arrays having a floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array
xhas an integer data type, the returned array must have the default real-valued floating-point data type.
Special Cases
Let
Mequal the number of elements over which to compute the arithmetic mean. For real-valued operands,If
Mis0, the arithmetic mean must beNaN.If
x_iisNaN, the arithmetic mean must beNaN(i.e.,NaNvalues propagate).
For complex floating-point operands, real-valued floating-point special cases should independently apply to the real and imaginary component operations involving real numbers. For example, let
a = real(x_i)andb = imag(x_i), andIf
Mis0, the arithmetic mean must beNaN + NaN j.If
aisNaN, the real component of the result must beNaN.Similarly, if
bisNaN, the imaginary component of the result must beNaN.
Note
Array libraries, such as NumPy, PyTorch, and JAX, currently deviate from this specification in their handling of components which are
NaNwhen computing the arithmetic mean. In general, consumers of array libraries implementing this specification are recommended to useisnan()to test whether the result of computing the arithmetic mean over an array have a complex floating-point data type isNaN, rather than relying onNaNpropagation of individual components.Changed in version 2024.12: Added complex data type support.
- meshgrid: meshgrid[TArray]¶
Returns coordinate matrices from coordinate vectors.
- Parameters:
arrays (array) – an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type.
indexing (Literal["xy", "ij"]) – Cartesian
'xy'or matrix'ij'indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), theindexingkeyword has no effect and should be ignored. Default:'xy'.
- Returns:
out – tuple of N arrays, where
Nis the number of provided one-dimensional input arrays. Each returned array must have rankN. ForNone-dimensional arrays having lengthsNi = len(xi),if matrix indexing
ij, then each returned array must have the shape(N1, N2, N3, ..., Nn).if Cartesian indexing
xy, then each returned array must have shape(N2, N1, N3, ..., Nn).
Accordingly, for the two-dimensional case with input one-dimensional arrays of length
MandN, if matrix indexingij, then each returned array must have shape(M, N), and, if Cartesian indexingxy, then each returned array must have shape(N, M).Similarly, for the three-dimensional case with input one-dimensional arrays of length
M,N, andP, if matrix indexingij, then each returned array must have shape(M, N, P), and, if Cartesian indexingxy, then each returned array must have shape(N, M, P).Each returned array should have the same data type as the input arrays.
- Return type:
Tuple[array, …]
Notes
Changed in version 2022.12: Added complex data type support.
Changed in version 2025.12: Changed the return value from a List to a Tuple.
- min: min[TArray]¶
Calculates the minimum value of the input array
x.- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute minimum values. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the minimum value is computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as
x.- Return type:
array
Notes
When the number of elements over which to compute the minimum value is zero, the minimum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if
xis a floating-point input array, returnNaN), or return the maximum possible value for the input arrayxdata type (e.g., ifxis a floating-point array, return+infinity).The order of signed zeros is unspecified and thus implementation-defined. When choosing between
-0or+0as a minimum value, specification-compliant libraries may choose to return either value.For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see complex-number-ordering).
Special Cases
For floating-point operands,
If
x_iisNaN, the minimum value must beNaN(i.e.,NaNvalues propagate).
Changed in version 2023.12: Clarified that the order of signed zeros is implementation-defined.
- minimum: minimum[TArray]¶
Computes the minimum value for each element
x1_iof the input arrayx1relative to the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise minimum values. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.The order of signed zeros is unspecified and thus implementation-defined. When choosing between
-0or+0as a minimum value, specification-compliant libraries may choose to return either value.For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see complex-number-ordering).
Special Cases
For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.
Added in version 2023.12.
Changed in version 2024.12: Added scalar argument support.
- moveaxis: moveaxis[TArray]¶
Moves array axes to new positions, while leaving other axes in their original positions.
- Parameters:
x (array) – input array.
source (Union[int, Tuple[int, ...]]) – axis (or axes) to move. Provided source axes must be unique. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.destination (Union[int, Tuple[int, ...]]) – axis (or axes) defining the desired position(s) for each respective
sourceaxis index. Provided destination axes must be unique. A valid axis must be an integer on the interval[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.
- Returns:
out – an array containing reordered axes. The returned array must have the same data type as
x.- Return type:
array
Notes
Added in version 2023.12.
- multiply: multiply[TArray]¶
Calculates the product for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
Floating-point multiplication is not always associative due to finite precision.
- Parameters:
x1 (Union[array, int, float, complex]) – first input array. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – second input array. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise products. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For real-valued floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis either+infinityor-infinityandx2_iis either+0or-0, the result isNaN.If
x1_iis either+0or-0andx2_iis either+infinityor-infinity, the result isNaN.If
x1_iandx2_ihave the same mathematical sign, the result has a positive mathematical sign, unless the result isNaN. If the result isNaN, the “sign” ofNaNis implementation-defined.If
x1_iandx2_ihave different mathematical signs, the result has a negative mathematical sign, unless the result isNaN. If the result isNaN, the “sign” ofNaNis implementation-defined.If
x1_iis either+infinityor-infinityandx2_iis either+infinityor-infinity, the result is a signed infinity with the mathematical sign determined by the rule already stated above.If
x1_iis either+infinityor-infinityandx2_iis a nonzero finite number, the result is a signed infinity with the mathematical sign determined by the rule already stated above.If
x1_iis a nonzero finite number andx2_iis either+infinityor-infinity, the result is a signed infinity with the mathematical sign determined by the rule already stated above.In the remaining cases, where neither
infinitynorNaNis involved, the product must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported rounding mode. If the magnitude is too large to represent, the result is an infinity of appropriate mathematical sign. If the magnitude is too small to represent, the result is a zero of appropriate mathematical sign.
For complex floating-point operands, multiplication is defined according to the following table. For real components
aandcand imaginary componentsbandd,c
dj
c + dj
a
a * c
(a*d)j
(a*c) + (a*d)j
bj
(b*c)j
-(b*d)
-(b*d) + (b*c)j
a + bj
(a*c) + (b*c)j
-(b*d) + (a*d)j
special rules
In general, for complex floating-point operands, real-valued floating-point special cases must independently apply to the real and imaginary component operations involving real numbers as described in the above table.
When
a,b,c, ordare all finite numbers (i.e., a value other thanNaN,+infinity, or-infinity), multiplication of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number multiplication\[(a + bj) \cdot (c + dj) = (ac - bd) + (bc + ad)j\]When at least one of
a,b,c, ordisNaN,+infinity, or-infinity,If
a,b,c, anddare allNaN, the result isNaN + NaN j.In the remaining cases, the result is implementation dependent.
Note
For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is
NaN, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations.Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- nan: TArray¶
IEEE 754 floating-point representation of Not a Number (
NaN).
- negative: negative[TArray]¶
Computes the numerical negative of each element
x_i(i.e.,y_i = -x_i) of the input arrayx.Note
For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent.
Note
If
xhas a complex floating-point data type, both the real and imaginary components for eachx_imust be negated (a result which follows from the rules of complex number multiplication).- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- newaxis: TArray¶
An alias for
Nonewhich is useful for indexing arrays.
- nextafter: nextafter[TArray]¶
Returns the next representable floating-point value for each element
x1_iof the input arrayx1in the direction of the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have the same data type asx1.
- Returns:
out – an array containing the element-wise results. The returned array must have the same data type as
x1.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For real-valued floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis-0andx2_iis+0, the result is+0.If
x1_iis+0andx2_iis-0, the result is-0.
Added in version 2024.12.
- nonzero: nonzero[TArray]¶
Returns the indices of the array elements which are non-zero.
Data-dependent output shape
The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. Must have one or more dimensions. If
xis zero-dimensional, the function must raise an exception.- Returns:
out – a tuple of
karrays, one for each dimension ofxand each of sizen(wherenis the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must be returned in row-major, C-style order. The returned array must have the default array index data type.- Return type:
Tuple[array, …]
Notes
If
xhas a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero.If
xhas a boolean data type, non-zero elements are those elements which are equal toTrue.
Changed in version 2022.12: Added complex data type support.
- not_equal: not_equal[TArray]¶
Computes the truth value of
x1_i != x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special Cases
For real-valued floating-point operands,
If
x1_iisNaNorx2_iisNaN, the result isTrue.If
x1_iis+infinityandx2_iis-infinity, the result isTrue.If
x1_iis-infinityandx2_iis+infinity, the result isTrue.If
x1_iis a finite number,x2_iis a finite number, andx1_idoes not equalx2_i, the result isTrue.In the remaining cases, the result is
False.
For complex floating-point operands, let
a = real(x1_i),b = imag(x1_i),c = real(x2_i),d = imag(x2_i), andIf
a,b,c, ordisNaN, the result isTrue.In the remaining cases, the result is the logical OR of the equality comparison between the real values
aandc(real components) and between the real valuesbandd(imaginary components), as described above for real-valued floating-point operands (i.e.,a != c OR b != d).
Note
For discussion of complex number equality, see complex-numbers.
Note
Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- ones: ones[TArray, TDtype, TDevice]¶
Returns a new array having a specified
shapeand filled with ones.Note
An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e.,
1 + 0j).- Parameters:
shape (Union[int, Tuple[int, ...]]) – output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array containing ones.
- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- ones_like: ones_like[TArray, TDtype, TDevice]¶
Returns a new array filled with ones and having the same
shapeas an input arrayx.Note
An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e.,
1 + 0j).- Parameters:
x (array) – input array from which to derive the output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be inferred fromx. Default:None.device (Optional[device]) – device on which to place the created array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the same shape as
xand filled with ones.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- permute_dims: permute_dims[TArray]¶
Permutes the axes of an array
x.- Parameters:
x (array) – input array.
axes (Tuple[int, ...]) – tuple containing a permutation of axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the respective axis index by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.
- Returns:
out – an array containing the axes permutation. The returned array must have the same data type as
x.- Return type:
array
Notes
Changed in version 2025.12: Added support for negative axes.
- pi: TArray¶
IEEE 754 floating-point representation of the mathematical constant
π.pi = 3.1415926535897932384626433...
- positive: positive[TArray]¶
Computes the numerical positive of each element
x_i(i.e.,y_i = +x_i) of the input arrayx.- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- pow: pow[TArray]¶
Calculates an implementation-dependent approximation of exponentiation by raising each element
x1_i(the base) of the input arrayx1to the power ofx2_i(the exponent), wherex2_iis the corresponding element of the input arrayx2.- Parameters:
x1 (Union[array, int, float, complex]) – first input array whose elements correspond to the exponentiation base. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – second input array whose elements correspond to the exponentiation exponent. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.If both
x1andx2have integer data types, the result ofpowwhenx2_iis negative (i.e., less than zero) is unspecified and thus implementation-dependent.If
x1has an integer data type andx2has a floating-point data type, behavior is implementation-dependent (type promotion between data type “kinds” (integer versus floating-point) is unspecified).By convention, the branch cut of the natural logarithm is the negative real axis \((-\infty, 0)\).
The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to
exp(x2*log(x1)), exponentiation has the same branch cut forx1as the natural logarithm (seelog()).Note: branch cuts follow C99 and have provisional status (see branch-cuts).
Special cases
For real-valued floating-point operands,
If
x1_iis not equal to1andx2_iisNaN, the result isNaN.If
x2_iis+0, the result is1, even ifx1_iisNaN.If
x2_iis-0, the result is1, even ifx1_iisNaN.If
x1_iisNaNandx2_iis not equal to0, the result isNaN.If
abs(x1_i)is greater than1andx2_iis+infinity, the result is+infinity.If
abs(x1_i)is greater than1andx2_iis-infinity, the result is+0.If
abs(x1_i)is1andx2_iis+infinity, the result is1.If
abs(x1_i)is1andx2_iis-infinity, the result is1.If
x1_iis1andx2_iis notNaN, the result is1.If
abs(x1_i)is less than1andx2_iis+infinity, the result is+0.If
abs(x1_i)is less than1andx2_iis-infinity, the result is+infinity.If
x1_iis+infinityandx2_iis greater than0, the result is+infinity.If
x1_iis+infinityandx2_iis less than0, the result is+0.If
x1_iis-infinity,x2_iis greater than0, andx2_iis an odd integer value, the result is-infinity.If
x1_iis-infinity,x2_iis greater than0, andx2_iis not an odd integer value, the result is+infinity.If
x1_iis-infinity,x2_iis less than0, andx2_iis an odd integer value, the result is-0.If
x1_iis-infinity,x2_iis less than0, andx2_iis not an odd integer value, the result is+0.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis+0andx2_iis less than0, the result is+infinity.If
x1_iis-0,x2_iis greater than0, andx2_iis an odd integer value, the result is-0.If
x1_iis-0,x2_iis greater than0, andx2_iis not an odd integer value, the result is+0.If
x1_iis-0,x2_iis less than0, andx2_iis an odd integer value, the result is-infinity.If
x1_iis-0,x2_iis less than0, andx2_iis not an odd integer value, the result is+infinity.If
x1_iis less than0,x1_iis a finite number,x2_iis a finite number, andx2_iis not an integer value, the result isNaN.
For complex floating-point operands, special cases should be handled as if the operation is implemented as
exp(x2*log(x1)).Note
Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification.
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- prod: prod[TArray, TDtype]¶
Calculates the product of input array
xelements.- Parameters:
x (array) – input array. Should have a numeric data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute products. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the sum (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the product is computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the
dtypeparameter above.- Return type:
array
Notes
Special Cases
Let
Mequal the number of elements over which to compute the product.If
Mis0, the product must be 1 (i.e., the empty product).
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
multiply().Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array.
- real: real[TArray]¶
Returns the real component of a complex number for each element
x_iof the input arrayx.- Parameters:
x (array) – input array. Must have a numeric data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as
x(e.g., ifxiscomplex64, the returned array must have the floating-point data typefloat32).- Return type:
array
Notes
Whether the returned array and the input array share the same underlying memory is unspecified and thus implementation-defined.
Added in version 2022.12.
Changed in version 2024.12: Added support for real-valued arrays.
- reciprocal: reciprocal[TArray]¶
Returns the reciprocal for each element
x_iof the input arrayx.- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type determined by type-promotion.
- Return type:
array
Notes
Special cases
For floating-point operands, special cases must be handled as if the operation is implemented as
1.0 / x(seedivide()).Added in version 2024.12.
- remainder: remainder[TArray]¶
Returns the remainder of division for each element
x1_iof the input arrayx1and the respective elementx2_iof the input arrayx2.Note
This function is equivalent to the Python modulus operator
x1_i % x2_i.- Parameters:
x1 (Union[array, int, float]) – dividend input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – divisor input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. Each element-wise result must have the same sign as the respective element
x2_i. The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
At least one of
x1orx2must be an array.For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined.
Special cases
Note
In general, similar to Python’s
%operator, this function is not recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility.For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis either+infinityor-infinityandx2_iis either+infinityor-infinity, the result isNaN.If
x1_iis either+0or-0andx2_iis either+0or-0, the result isNaN.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis-0andx2_iis greater than0, the result is+0.If
x1_iis+0andx2_iis less than0, the result is-0.If
x1_iis-0andx2_iis less than0, the result is-0.If
x1_iis greater than0andx2_iis+0, the result isNaN.If
x1_iis greater than0andx2_iis-0, the result isNaN.If
x1_iis less than0andx2_iis+0, the result isNaN.If
x1_iis less than0andx2_iis-0, the result isNaN.If
x1_iis+infinityandx2_iis a positive (i.e., greater than0) finite number, the result isNaN.If
x1_iis+infinityandx2_iis a negative (i.e., less than0) finite number, the result isNaN.If
x1_iis-infinityandx2_iis a positive (i.e., greater than0) finite number, the result isNaN.If
x1_iis-infinityandx2_iis a negative (i.e., less than0) finite number, the result isNaN.If
x1_iis a positive (i.e., greater than0) finite number andx2_iis+infinity, the result isx1_i. (note: this result matches Python behavior.)If
x1_iis a positive (i.e., greater than0) finite number andx2_iis-infinity, the result isx2_i. (note: this result matches Python behavior.)If
x1_iis a negative (i.e., less than0) finite number andx2_iis+infinity, the result isx2_i. (note: this results matches Python behavior.)If
x1_iis a negative (i.e., less than0) finite number andx2_iis-infinity, the result isx1_i. (note: this result matches Python behavior.)In the remaining cases, the result must match that of the Python
%operator.
Changed in version 2024.12: Added scalar argument support.
- repeat: repeat[TArray]¶
Repeats each element of an array a specified number of times on a per-element basis.
Data-dependent output shape
When
repeatsis an array, the shape of the output array for this function depends on the data values in therepeatsarray; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing the values inrepeats. Accordingly, such libraries may choose to omit support forrepeatsarrays; however, conforming implementations must support providing a literalint. See data-dependent-output-shapes section for more details.- Parameters:
x (array) – input array containing elements to repeat.
repeats (Union[int, array]) –
the number of repetitions for each element.
If
axisisNone, letM = prod(x.shape)andif
repeatsis an array,repeatsmust be broadcast compatible with the shape(M,)(i.e., be a one-dimensional array having shape(1,)or(M,)).if
repeatsis an integer,repeatsmust be broadcasted to the shape (M,).
If
axisis notNone, letS = x.shape[axis]andif
repeatsis an array,repeatsmust be broadcast compatible with the shape(S,)(i.e., be a one-dimensional array having shape(1,)or(S,)).if
repeatsis an integer,repeatsmust be broadcasted to the shape(S,).
If
repeatsis an array, the array must have an integer data type.axis (Optional[int]) – the axis along which to repeat elements. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Ifaxisis None, the function must flatten the input arrayxand then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array must be flattened in row-major, C-style order. Default:None.
- Returns:
out – an output array containing repeated elements. The returned array must have the same data type as
x. IfaxisisNone, the returned array must be a one-dimensional array; otherwise, the returned array must have the same shape asx, except for the axis along which elements were repeated.- Return type:
array
Notes
For specification-conforming array libraries supporting hardware acceleration, providing an array for
repeatscan cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries should include a warning in their documentation regarding potential performance degradation whenrepeatsis an array.
Added in version 2023.12.
- reshape: reshape[TArray]¶
Reshapes an array without changing its data.
- Parameters:
x (array) – input array to reshape.
shape (Tuple[int, ...]) – a new shape compatible with the original shape. Only one shape dimension must be allowed to be
-1. When a shape dimension is-1, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions.copy (Optional[bool]) – whether or not to copy the input array. If
True, the function must always copy (see copy-keyword-argument). IfFalse, the function must never copy. IfNone, the function must avoid copying, if possible, and may copy otherwise. Default:None.
- Returns:
out – an output array. The returned array must have the same data type and the same elements as
x.- Return type:
array
- Raises:
ValueError – If
copy=Falseand a copy would be necessary, aValueErrorshould be raised.
- result_type: result_type[TArray, TDtype]¶
Returns the dtype that results from applying type promotion rules (see type-promotion) to the arguments.
- Parameters:
arrays_and_dtypes (Union[array, int, float, complex, bool, dtype]) – an arbitrary number of input arrays, scalars, and/or dtypes.
- Returns:
out – the dtype resulting from an operation involving the input arrays, scalars, and/or dtypes.
- Return type:
Notes
At least one argument must be an array or a dtype.
If provided array and/or dtype arguments having mixed data type kinds (e.g., integer and floating-point), the returned dtype is unspecified and thus implementation-dependent.
If at least one argument is an array, the function must determine the resulting dtype according to the type promotion graph of the array device which is shared among all array arguments. As not all devices can support all data types, full support for type promotion rules (see type-promotion) may not be possible. Accordingly, the returned dtype may differ from that determined from the complete type promotion graph defined in this specification (see type-promotion).
If two or more arguments are arrays belonging to different devices, behavior is unspecified and thus implementation-dependent. Conforming implementations may choose to ignore device attributes, raise an exception, or some other behavior.
Changed in version 2024.12: Added scalar argument support.
Changed in version 2024.12: Required that the application of type promotion rules must account for device context.
- roll: roll[TArray]¶
Rolls array elements along a specified axis.
Array elements that roll beyond the last position are re-introduced at the first position.
Array elements that roll beyond the first position are re-introduced at the last position.
- Parameters:
x (array) – input array.
shift (Union[int, Tuple[int, ...]]) – number of places by which the elements are shifted. If
shiftis a tuple, thenaxismust be a tuple of the same size, and each of the given axes must be shifted by the corresponding element inshift. Ifshiftis anintandaxisa tuple, then the sameshiftmust be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension ofaxis. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension ofaxis.axis (Optional[Union[int, Tuple[int, ...]]]) – axis (or axes) along which elements to shift. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. IfaxisisNone, the array must be flattened, shifted, and then restored to its original shape. Default:None.
- Returns:
out – an output array. The returned array must have the same data type as
x. The returned array must have the same elements asx, but which are shifted relative tox.- Return type:
array
- round: round[TArray]¶
Rounds each element
x_iof the input arrayxto the nearest integer-valued number.Note
For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number.
Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued
x,real(round(x))must equalround(real(x)))andimag(round(x))must equalround(imag(x))).- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the rounded result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
Note
For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if
real(x_i)isNaN, the rounded real component isNaN).If
x_iis already integer-valued, the result isx_i.
For floating-point operands,
If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iisNaN, the result isNaN.If two integers are equally close to
x_i, the result is the even integer closest tox_i.
Changed in version 2022.12: Added complex data type support.
- searchsorted: searchsorted[TArray]¶
Finds the indices into
x1such that, if the corresponding elements inx2were inserted before the indices, the order ofx1, when sorted in ascending order, would be preserved.- Parameters:
x1 (array) – input array. Must be a one-dimensional array. Should have a real-valued data type. If
sorterisNone, must be sorted in ascending order; otherwise,sortermust be an array of indices that sortx1in ascending order.x2 (Union[array, int, float]) – array containing search values. Should have a real-valued data type.
side (Literal['left', 'right']) –
argument controlling which index is returned if a value lands exactly on an edge.
Let
vbe an element ofx2given byv = x2[j], wherejrefers to a valid index (see indexing).If
vis less than all elements inx1, thenout[j]must be0.If
vis greater than all elements inx1, thenout[j]must beM, whereMis the number of elements inx1.Otherwise, each returned index
i = out[j]must satisfy an index condition:If
side == 'left', thenx1[i-1] < v <= x1[i].If
side == 'right', thenx1[i-1] <= v < x1[i].
Default:
'left'.sorter (Optional[array]) – array of indices that sort
x1in ascending order. The array must have the same shape asx1and have an integer data type. Default:None.
- Returns:
out – an array of indices with the same shape as
x2. The returned array must have the default array index data type.- Return type:
array
Notes
If
x2is a scalar value,x2should be treated as equivalent to a zero-dimensional array having a data type determined according to mixing-scalars-and-arrays.For real-valued floating-point arrays, the sort order of NaNs and signed zeros is unspecified and thus implementation-dependent. Accordingly, when a real-valued floating-point array contains NaNs and signed zeros, what constitutes ascending order may vary among specification-conforming array libraries.
While behavior for arrays containing NaNs and signed zeros is implementation-dependent, specification-conforming libraries should, however, ensure consistency with
sortandargsort(i.e., if a value inx2is inserted intox1according to the corresponding index in the output array andsortis invoked on the resultant array, the sorted result should be an array in the same order).
Added in version 2023.12.
Changed in version 2024.12: Fixed incorrect boundary conditions.
Changed in version 2025.12: Added scalar argument support.
- sign: sign[TArray]¶
Returns an indication of the sign of a number for each element
x_iof the input arrayx.The sign function (also known as the signum function) of a number \(x_i\) is defined as
\[\begin{split}\operatorname{sign}(x_i) = \begin{cases} 0 & \textrm{if } x_i = 0 \\ \frac{x_i}{|x_i|} & \textrm{otherwise} \end{cases}\end{split}\]where \(|x_i|\) is the absolute value of \(x_i\).
- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
For real-valued operands,
If
x_iis less than0, the result is-1.If
x_iis either-0or+0, the result is0.If
x_iis greater than0, the result is+1.If
x_iisNaN, the result isNaN.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either-0or+0andbis either-0or+0, the result is0 + 0j.If
aisNaNorbisNaN, the result isNaN + NaN j.In the remaining cases, special cases must be handled according to the rules of complex number division (see
divide()).
Changed in version 2022.12: Added complex data type support.
- signbit: signbit[TArray]¶
Determines whether the sign bit is set for each element
x_iof the input arrayx.The sign bit of a real-valued floating-point number
x_iis set wheneverx_iis either-0, less than zero, or a signedNaN(i.e., aNaNvalue whose sign bit is1).- Parameters:
x (array) – input array. Should have a real-valued floating-point data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a data type ofbool.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iis+0, the result isFalse.If
x_iis-0, the result isTrue.If
x_iis+infinity, the result isFalse.If
x_iis-infinity, the result isTrue.If
x_iis a positive (i.e., greater than0) finite number, the result isFalse.If
x_iis a negative (i.e., less than0) finite number, the result isTrue.If
x_iisNaNand the sign bit ofx_iis0, the result isFalse.If
x_iisNaNand the sign bit ofx_iis1, the result isTrue.
Added in version 2023.12.
- sin: sin[TArray]¶
Calculates an implementation-dependent approximation to the sine for each element
x_iof the input arrayx.Each element
x_iis assumed to be expressed in radians.Note
The sine is an entire function on the complex plane and has no branch cuts.
Note
For complex arguments, the mathematical definition of sine is
\[\begin{split}\begin{align} \operatorname{sin}(x) &= \frac{e^{jx} - e^{-jx}}{2j} \\ &= \frac{\operatorname{sinh}(jx)}{j} \\ &= \frac{\operatorname{sinh}(jx)}{j} \cdot \frac{j}{j} \\ &= -j \cdot \operatorname{sinh}(jx) \end{align}\end{split}\]where \(\operatorname{sinh}\) is the hyperbolic sine.
- Parameters:
x (array) – input array whose elements are each expressed in radians. Should have a floating-point data type.
- Returns:
out – an array containing the sine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis either+infinityor-infinity, the result isNaN.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
-1j * sinh(x*1j).Changed in version 2022.12: Added complex data type support.
- sinh: sinh[TArray]¶
Calculates an implementation-dependent approximation to the hyperbolic sine for each element
x_iof the input arrayx.The mathematical definition of the hyperbolic sine is
\[\operatorname{sinh}(x) = \frac{e^x - e^{-x}}{2}\]Note
The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period \(2\pi j\), with respect to the imaginary component.
- Parameters:
x (array) – input array whose elements each represent a hyperbolic angle. Should have a floating-point data type.
- Returns:
out – an array containing the hyperbolic sine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
Note
For all operands,
sinh(x)must equal-sinh(-x).For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andNote
For complex floating-point operands,
sinh(conj(x))must equalconj(sinh(x)).If
ais+0andbis+0, the result is+0 + 0j.If
ais+0andbis+infinity, the result is0 + NaN j(sign of the real component is unspecified).If
ais+0andbisNaN, the result is0 + NaN j(sign of the real component is unspecified).If
ais a positive (i.e., greater than0) finite number andbis+infinity, the result isNaN + NaN j.If
ais a positive (i.e., greater than0) finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis+0, the result is+infinity + 0j.If
ais+infinityandbis a positive finite number, the result is+infinity * cis(b).If
ais+infinityandbis+infinity, the result isinfinity + NaN j(sign of the real component is unspecified).If
ais+infinityandbisNaN, the result isinfinity + NaN j(sign of the real component is unspecified).If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis a nonzero finite number, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
where
cis(v)iscos(v) + sin(v)*1j.Changed in version 2022.12: Added complex data type support.
- sort: sort[TArray]¶
Returns a sorted copy of an input array
x.- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (int) – axis along which to sort. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:-1.descending (bool) – sort order. If
True, the array must be sorted in descending order (by value). IfFalse, the array must be sorted in ascending order (by value). Default:False.stable (bool) – sort stability. If
True, the returned array must maintain the relative order ofxvalues which compare as equal. IfFalse, the returned array may maintain the relative order ofxvalues which compare as equal (i.e., the relative order ofxvalues which compare as equal is implementation-dependent). Default:True.
- Returns:
out – a sorted array. The returned array must have the same data type and shape as
x.- Return type:
array
Notes
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
- sqrt: sqrt[TArray]¶
Calculates the principal square root for each element
x_iof the input arrayx.Note
After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754).
Note
For complex floating-point operands,
sqrt(conj(x))must equalconj(sqrt(x)).Note
By convention, the branch cut of the square root is the negative real axis \((-\infty, 0)\).
The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component.
Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by \([0, +\infty)\) along the real axis and \((-\infty, +\infty)\) along the imaginary axis).
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the square root of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than0, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result is+0 + 0j.If
ais any value (includingNaN) andbis+infinity, the result is+infinity + infinity j.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
a-infinityandbis a positive (i.e., greater than0) finite number, the result is+0 + infinity j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0 j.If
ais-infinityandbisNaN, the result isNaN + infinity j(sign of the imaginary component is unspecified).If
ais+infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis any value, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- square: square[TArray]¶
Squares each element
x_iof the input arrayx.The square of a number
x_iis defined as\[x_i^2 = x_i \cdot x_i\]- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
Special cases
For floating-point operands, special cases must be handled as if the operation is implemented as
x * x(seemultiply()).Changed in version 2022.12: Added complex data type support.
- squeeze: squeeze[TArray]¶
Removes singleton axes from
x.- Parameters:
x (array) – input array.
axis (Union[int, Tuple[int, ...]]) – axis (or axes) to squeeze. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.
- Returns:
out – an output array. The returned array must have the same data type and the same elements as
x.- Return type:
array
- Raises:
ValueError – If a specified axis has a size greater than one (i.e., it is not a singleton axis), a
ValueErrorshould be raised.
- stack: stack[TArray]¶
Joins a sequence of arrays along a new axis.
- Parameters:
arrays (Union[Tuple[array, ...], List[array]]) – input arrays to join. Each array must have the same shape.
axis (int) – axis along which to join the arrays. Providing an
axisspecifies the index of the new axis in the shape of the result. For example, ifaxisis0, the new axis must be the first dimension and the output array must have shape(N, A, B, C); ifaxisis1, the new axis will be the second dimension and the output array will have shape(A, N, B, C); and, ifaxisis-1, the new axis will be the last dimension and the output array will have shape(A, B, C, N). A valid axis must be an integer on the interval[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:0.
- Returns:
out – an output array. The returned array must have
N+1axes, whereNis the number of axes inx. If the input arrays have different data types, normal type-promotion must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays.- Return type:
array
Notes
This specification leaves type promotion between data type families (i.e.,
intxxandfloatxx) unspecified and thus implementation-defined.
- std: std[TArray]¶
Calculates the standard deviation of the input array
x.- Parameters:
x (array) – input array. Should have a real-valued floating-point data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute standard deviations. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.correction (Union[int, float]) – degrees of freedom adjustment. Setting this parameter to a value other than
0has the effect of adjusting the divisor during the calculation of the standard deviation according toM-cwhereMcorresponds to the total number of elements over which the standard deviation is computed andccorresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to0is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to1is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel’s correction). Default:0.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the standard deviation is computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as
x.- Return type:
array
Notes
While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array
xhas an integer data type, the returned array must have the default real-valued floating-point data type.
Special Cases
Let
Mequal the number of elements over which to compute the standard deviation.If
M - correctionis less than or equal to0, the standard deviation must beNaN.If
x_iisNaN, the standard deviation must beNaN(i.e.,NaNvalues propagate).
- subtract: subtract[TArray]¶
Calculates the difference for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float, complex]) – first input array. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – second input array. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise differences. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.The result of
x1_i - x2_imust be the same asx1_i + (-x2_i)and must be governed by the same floating-point rules as addition (seeadd()).
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- sum: sum[TArray, TDtype]¶
Calculates the sum of the input array
x.- Parameters:
x (array) – input array. Should have a numeric data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the sum (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the sum is computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the
dtypeparameter above.- Return type:
array
Notes
Special Cases
Let
Mequal the number of elements over which to compute the sum.If
Mis0, the sum must be0(i.e., the empty sum).
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
add().Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array.
- take: take[TArray]¶
Returns elements of an array along an axis.
- Parameters:
x (array) – input array. Should have one or more axes.
indices (array) – array indices. The array must be one-dimensional and have an integer data type. If an index is negative, the function must determine the element to select along a specified axis by counting from the last element (where
-1refers to the last element).axis (Optional[int]) –
axis over which to select values. If
axisis negative, the function must determine the axis along which to select values by counting from the last axis (where-1refers to the last axis).If
xis a one-dimensional array, providing anaxismust be optional; however, ifxhas more than one axis, providing anaxismust be required.
- Returns:
out – an array having the same data type as
x. The output array must have the same number of axes asxand must have the same shape asx, except for the axis specified byaxiswhose size must equal the number of elements inindices.- Return type:
array
Notes
This specification does not require bounds checking. The behavior for out-of-bounds indices is unspecified and thus implementation-defined.
When
xis a zero-dimensional array, behavior is unspecified and thus implementation-defined.
Added in version 2022.12.
Changed in version 2023.12: Out-of-bounds behavior is explicitly left unspecified.
Changed in version 2024.12: Behavior when provided a zero-dimensional input array is explicitly left unspecified.
Changed in version 2024.12: Clarified support for negative indices.
- take_along_axis: take_along_axis[TArray]¶
Returns elements from an array at the one-dimensional indices specified by
indicesalong a providedaxis.- Parameters:
x (array) – input array. Must be compatible with
indices, except for the axis specified byaxis(see broadcasting).indices (array) – array indices. Must have the same number of axes as
xand must be compatible withx, except for the axis specified byaxis(see broadcasting). If an index is negative, the function must determine the element to select along a specified axis by counting from the last element (where-1refers to the last element).axis (int) – axis along which to select values. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:-1.
- Returns:
out – an array containing elements from
x. The returned array must have the same data type asx. The returned array must have the same number of axes asxand must have a shape determined according to broadcasting, except for the axis specified byaxiswhose size must equal the size of the corresponding axis inindices.- Return type:
array
Notes
This specification does not require bounds checking. The behavior for out-of-bounds indices is unspecified and thus implementation-defined.
Added in version 2024.12.
- tan: tan[TArray]¶
Calculates an implementation-dependent approximation to the tangent for each element
x_iof the input arrayx.Each element
x_iis assumed to be expressed in radians.Note
Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period \(\pi j\), with respect to the real component and has first order poles along the real line at coordinates \((\pi (\frac{1}{2} + n), 0)\). However, IEEE 754 binary floating-point representation cannot represent the value \(\pi / 2\) exactly, and, thus, no argument value is possible for which a pole error occurs.
Note
For complex arguments, the mathematical definition of tangent is
\[\begin{split}\begin{align} \operatorname{tan}(x) &= \frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\ &= (-1) \frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\ &= -j \cdot \operatorname{tanh}(jx) \end{align}\end{split}\]where \(\operatorname{tanh}\) is the hyperbolic tangent.
- Parameters:
x (array) – input array whose elements are expressed in radians. Should have a floating-point data type.
- Returns:
out – an array containing the tangent of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis either+infinityor-infinity, the result isNaN.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
-1j * tanh(x*1j).Changed in version 2022.12: Added complex data type support.
- tanh: tanh[TArray]¶
Calculates an implementation-dependent approximation to the hyperbolic tangent for each element
x_iof the input arrayx.The mathematical definition of the hyperbolic tangent is
\[\begin{split}\begin{align} \operatorname{tanh}(x) &= \frac{\operatorname{sinh}(x)}{\operatorname{cosh}(x)} \\ &= \frac{e^x - e^{-x}}{e^x + e^{-x}} \end{align}\end{split}\]where \(\operatorname{sinh}(x)\) is the hyperbolic sine and \(\operatorname{cosh}(x)\) is the hyperbolic cosine.
Note
The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period \(\pi j\), with respect to the imaginary component and has first order poles along the imaginary line at coordinates \((0, \pi (\frac{1}{2} + n))\). However, IEEE 754 binary floating-point representation cannot represent \(\pi / 2\) exactly, and, thus, no argument value is possible such that a pole error occurs.
- Parameters:
x (array) – input array whose elements each represent a hyperbolic angle. Should have a floating-point data type.
- Returns:
out – an array containing the hyperbolic tangent of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
Note
For all operands,
tanh(-x)must equal-tanh(x).For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+1.If
x_iis-infinity, the result is-1.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andNote
For complex floating-point operands,
tanh(conj(x))must equalconj(tanh(x)).If
ais+0andbis+0, the result is+0 + 0j.If
ais a nonzero finite number andbis+infinity, the result isNaN + NaN j.If
ais+0andbis+infinity, the result is+0 + NaN j.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais+0andbisNaN, the result is+0 + NaN j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is1 + 0j.If
ais+infinityandbis+infinity, the result is1 + 0j(sign of the imaginary component is unspecified).If
ais+infinityandbisNaN, the result is1 + 0j(sign of the imaginary component is unspecified).If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis a nonzero number, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Warning
For historical reasons stemming from the C standard, array libraries may not return the expected result when
ais+0andbis either+infinityorNaN. The result should be+0 + NaN jin both cases; however, for libraries compiled against older C versions, the result may beNaN + NaN j.Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases.
Changed in version 2022.12: Added complex data type support.
- tensordot: tensordot[TArray]¶
Returns a tensor contraction of
x1andx2over specific axes.- Parameters:
x1 (array) – first input array. Should have a numeric data type.
x2 (array) – second input array. Should have a numeric data type. Corresponding contracted axes of
x1andx2must be equal.axes (Union[int, Tuple[Sequence[int], Sequence[int]]]) –
number of axes to contract or explicit sequences of axis indices for
x1andx2, respectively.If
axesis anintequal toN, then contraction must be performed over the lastNaxes ofx1and the firstNaxes ofx2in order. The size of each corresponding axis must match. An integeraxesvalue must be nonnegative.If
Nequals0, the result must be the tensor (outer) product.If
Nequals1, the result must be the tensor dot product.If
Nequals2, the result must be the tensor double contraction (default).
If
axesis a tuple of two sequences(x1_axes, x2_axes), the first sequence must apply tox1and the second sequence must apply tox2. Both sequences must have the same length. Each axisx1_axes[i]forx1must have the same size as the respective axisx2_axes[i]forx2. Each index referred to in a sequence must be unique. A valid axis must be an integer on the interval[-S, S), whereSis the number of axes in respective array. Hence, ifx1hasNaxes, a validx1axes must be an integer on the interval[-N, N). Ifx2hasMaxes, a validx2axes must be an integer on the interval[-M, M). If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.
- Returns:
out – an array containing the tensor contraction. The returned array must have a shape which consists of the non-contracted axes of the first array
x1, followed by the non-contracted axes of the second arrayx2. The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
The
tensordotfunction corresponds to the generalized matrix product.Contracted axes must not be broadcasted.
If either
x1orx2has a complex floating-point data type, the function must not complex-conjugate or transpose either argument. If conjugation and/or transposition is desired, a user can explicitly perform these operations prior to computing the generalized matrix product.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Allow negative axes.
- tile: tile[TArray]¶
Constructs an array by tiling an input array.
- Parameters:
x (array) – input array.
repetitions (Tuple[int, ...]) –
number of repetitions along each axis.
Let
N = len(x.shape)andM = len(repetitions).If
N > M, the function must prepend ones until all axes are specified (e.g., ifxhas shape(8,6,4,2)andrepetitionsis the tuple(3,3), thenrepetitionsmust be treated as(1,1,3,3)).If
N < M, the function must prepend singleton axes toxuntilxhas as many axes asrepetitionsspecifies (e.g., ifxhas shape(4,2)andrepetitionsis the tuple(3,3,3,3), thenxmust be treated as if it has shape(1,1,4,2)).
- Returns:
out – a tiled output array. The returned array must have the same data type as
xand must have a number of axes equal tomax(N, M). IfSis the shape of the tiled array after prepending singleton dimensions (if necessary) andris the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis must satisfyS[i]*r[i], whereirefers to theith axis.- Return type:
array
Notes
Added in version 2023.12.
- tril: tril[TArray]¶
Returns the lower triangular part of a matrix (or a stack of matrices)
x.Note
The lower triangular part of the matrix is defined as the elements on and below the specified diagonal
k.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices.k (int) –
diagonal above which to zero elements. If
k = 0, the diagonal is the main diagonal. Ifk < 0, the diagonal is below the main diagonal. Ifk > 0, the diagonal is above the main diagonal. Default:0.Note
The main diagonal is defined as the set of indices
{(i, i)}forion the interval[0, min(M, N) - 1].
- Returns:
out – an array containing the lower triangular part(s). The returned array must have the same shape and data type as
x. All elements above the specified diagonalkmust be zeroed. The returned array should be allocated on the same device asx.- Return type:
array
- triu: triu[TArray]¶
Returns the upper triangular part of a matrix (or a stack of matrices)
x.Note
The upper triangular part of the matrix is defined as the elements on and above the specified diagonal
k.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices.k (int) –
diagonal below which to zero elements. If
k = 0, the diagonal is the main diagonal. Ifk < 0, the diagonal is below the main diagonal. Ifk > 0, the diagonal is above the main diagonal. Default:0.Note
The main diagonal is defined as the set of indices
{(i, i)}forion the interval[0, min(M, N) - 1].
- Returns:
out – an array containing the upper triangular part(s). The returned array must have the same shape and data type as
x. All elements below the specified diagonalkmust be zeroed. The returned array should be allocated on the same device asx.- Return type:
array
- trunc: trunc[TArray]¶
Rounds each element
x_iof the input arrayxto the nearest integer-valued number that is closer to zero thanx_i.- Parameters:
x (array) – input array. Should have a real-valued data type.
- Returns:
out – an array containing the rounded result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
If
x_iis already integer-valued, the result isx_i.
For floating-point operands,
If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iisNaN, the result isNaN.
- uint16: TDtype¶
- uint32: TDtype¶
- uint64: TDtype¶
- uint8: TDtype¶
- unique_all: unique_all[TArray]¶
Returns the unique elements of an input array
x, the first occurring indices for each unique element inx, the indices from the set of unique elements that reconstructx, and the corresponding counts for each unique element inx.Data-dependent output shape
The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, et cetera) can find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. If
xhas more than one dimension, the function must flattenxand return the unique elements of the flattened array.- Returns:
out – a namedtuple
(values, indices, inverse_indices, counts)whosefirst element must have the field name
valuesand must be a one-dimensional array containing the unique elements ofx. The array must have the same data type asx.second element must have the field name
indicesand must be an array containing the indices (first occurrences) of a flattenedxthat result invalues. The array must have the same shape asvaluesand must have the default array index data type.third element must have the field name
inverse_indicesand must be an array containing the indices ofvaluesthat reconstructx. The array must have the same shape asxand must have the default array index data type.fourth element must have the field name
countsand must be an array containing the number of times each unique element occurs inx. The order of the returned counts must match the order ofvalues, such that a specific element incountscorresponds to the respective unique element invalues. The returned array must have same shape asvaluesand must have the default array index data type.
- Return type:
Tuple[array, array, array, array]
Notes
The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order may vary between implementations.
Uniqueness should be determined based on value equality (see
equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.As
nanvalues compare asFalse,nanvalues should be considered distinct.As complex floating-point values having at least one
nancomponent compare asFalse, complex floating-point values havingnancomponents should be considered distinct.As
-0and+0compare asTrue, signed zeros should not be considered distinct, and the corresponding unique element may be implementation-defined (e.g., an implementation may choose to return-0if-0occurs before+0).
As signed zeros are not distinct, using
inverse_indicesto reconstruct the input array is not guaranteed to return an array having the exact same values.Each
nanvalue and each complex floating-point value having anancomponent should have a count of one, while the counts for signed zeros should be aggregated as a single count.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Clarified flattening behavior and required the order of
countsmatch the order ofvalues.
- unique_counts: unique_counts[TArray]¶
Returns the unique elements of an input array
xand the corresponding counts for each unique element inx.Data-dependent output shape
The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. If
xhas more than one dimension, the function must flattenxand return the unique elements of the flattened array.- Returns:
out – a namedtuple (values, counts) whose
first element must have the field name
valuesand must be a one-dimensional array containing the unique elements ofx. The array must have the same data type asx.second element must have the field name counts and must be an array containing the number of times each unique element occurs in
x. The order of the returned counts must match the order ofvalues, such that a specific element incountscorresponds to the respective unique element invalues. The returned array must have same shape asvaluesand must have the default array index data type.
- Return type:
Tuple[array, array]
Notes
The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order may vary between implementations.
Uniqueness should be determined based on value equality (see
equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.As
nanvalues compare asFalse,nanvalues should be considered distinct.As complex floating-point values having at least one
nancomponent compare asFalse, complex floating-point values havingnancomponents should be considered distinct.As
-0and+0compare asTrue, signed zeros should not be considered distinct, and the corresponding unique element may be implementation-defined (e.g., an implementation may choose to return-0if-0occurs before+0).
Each
nanvalue and each complex floating-point value having anancomponent should have a count of one, while the counts for signed zeros should be aggregated as a single count.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Clarified flattening behavior and required the order of
countsmatch the order ofvalues.
- unique_inverse: unique_inverse[TArray]¶
Returns the unique elements of an input array
xand the indices from the set of unique elements that reconstructx.Data-dependent output shape
The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. If
xhas more than one dimension, the function must flattenxand return the unique elements of the flattened array.- Returns:
out – a namedtuple
(values, inverse_indices)whosefirst element must have the field name
valuesand must be a one-dimensional array containing the unique elements ofx. The array must have the same data type asx.second element must have the field name
inverse_indicesand must be an array containing the indices ofvaluesthat reconstructx. The array must have the same shape asxand have the default array index data type.
- Return type:
Tuple[array, array]
Notes
The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order may vary between implementations.
Uniqueness should be determined based on value equality (see
equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.As
nanvalues compare asFalse,nanvalues should be considered distinct.As complex floating-point values having at least one
nancomponent compare asFalse, complex floating-point values havingnancomponents should be considered distinct.As
-0and+0compare asTrue, signed zeros should not be considered distinct, and the corresponding unique element may be implementation-defined (e.g., an implementation may choose to return-0if-0occurs before+0).
As signed zeros are not distinct, using
inverse_indicesto reconstruct the input array is not guaranteed to return an array having the exact same values.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Clarified flattening behavior.
- unique_values: unique_values[TArray]¶
Returns the unique elements of an input array
x.Data-dependent output shape
The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. If
xhas more than one dimension, the function must flattenxand return the unique elements of the flattened array.- Returns:
out – a one-dimensional array containing the set of unique elements in
x. The returned array must have the same data type asx.- Return type:
array
Notes
The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order may vary between implementations.
Uniqueness should be determined based on value equality (see
equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.As
nanvalues compare asFalse,nanvalues should be considered distinct.As complex floating-point values having at least one
nancomponent compare asFalse, complex floating-point values havingnancomponents should be considered distinct.As
-0and+0compare asTrue, signed zeros should not be considered distinct, and the corresponding unique element may be implementation-defined (e.g., an implementation may choose to return-0if-0occurs before+0).
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Required that the output array must be one-dimensional.
- unstack: unstack[TArray]¶
Splits an array into a sequence of arrays along the given axis.
- Parameters:
x (array) – input array.
axis (int) – axis along which to split an array. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:0.
- Returns:
out – tuple of slices along the given dimension. Each returned array must have the same shape.
- Return type:
Tuple[array, …]
Notes
Added in version 2023.12.
- var: var[TArray]¶
Calculates the variance of the input array
x.- Parameters:
x (array) – input array. Should have a real-valued floating-point data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.correction (Union[int, float]) – degrees of freedom adjustment. Setting this parameter to a value other than
0has the effect of adjusting the divisor during the calculation of the variance according toM-cwhereMcorresponds to the total number of elements over which the variance is computed andccorresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to0is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to1is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel’s correction). Default:0.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the variance is computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as
x.- Return type:
array
Notes
While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array
xhas an integer data type, the returned array must have the default real-valued floating-point data type.
Special Cases
Let
Mequal the number of elements over which to compute the variance.If
M - correctionis less than or equal to0, the variance must beNaN.If
x_iisNaN, the variance must beNaN(i.e.,NaNvalues propagate).
- vecdot: vecdot[TArray]¶
Computes the (vector) dot product of two arrays.
Let \(\mathbf{a}\) be a vector in
x1and \(\mathbf{b}\) be a corresponding vector inx2. The dot product is defined as\[\mathbf{a} \cdot \mathbf{b} = \sum_{i=0}^{n-1} \overline{a_i}b_i\]over the axis specified by
axisand where \(n\) is the axis size and \(\overline{a_i}\) denotes the complex conjugate if \(a_i\) is complex and the identity if \(a_i\) is real-valued.- Parameters:
x1 (array) – first input array. Should have a floating-point data type.
x2 (array) – second input array. Must be compatible with
x1for all non-contracted axes (see broadcasting). The size of the axis over which to compute the dot product must be the same size as the respective axis inx1. Should have a floating-point data type.axis (int) – axis of
x1andx2containing the vectors for which to compute the dot product. Should be an integer on the interval[-N, -1], whereNismin(x1.ndim, x2.ndim). The function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). By default, the function must compute the dot product over the last axis. Default:-1.
- Returns:
out – if
x1andx2are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and havingN-1axes, whereNis number of axes in the shape determined according to broadcasting along the non-contracted axes. The returned array must have a data type determined by type-promotion.- Return type:
array
- Raises:
Exception – an exception should be raised in the following circumstances: - if the size of the axis over which to compute the dot product is not the same (before broadcasting) for both
x1andx2.
Notes
The contracted axis must not be broadcasted.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Restricted
axisto only negative integers.
- where: where[TArray]¶
Returns elements chosen from
x1orx2depending oncondition.- Parameters:
condition (array) – when
True, yieldx1_i; otherwise, yieldx2_i. Should have a boolean data type. Must be broadcast-compatible withx1andx2(see broadcasting).x1 (Union[array, int, float, complex, bool]) – first input array. Must be broadcast-compatible with
conditionandx2(see broadcasting).x2 (Union[array, int, float, complex, bool]) – second input array. Must be broadcast-compatible with
conditionandx1(see broadcasting).
- Returns:
out – an array with elements from
x1whereconditionisTrue, and elements fromx2elsewhere. The returned array must have a data type determined by type-promotion rules with the arraysx1andx2.- Return type:
array
Notes
At least one of
x1andx2must be an array.If either
x1orx2is a scalar value, the returned array must have a data type determined according to mixing-scalars-and-arrays.
Changed in version 2024.12: Added scalar argument support.
Changed in version 2024.12: Clarified that the
conditionargument should have a boolean data type.
- zeros: zeros[TArray, TDtype, TDevice]¶
Returns a new array having a specified
shapeand filled with zeros.- Parameters:
shape (Union[int, Tuple[int, ...]]) – output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array containing zeros.
- Return type:
array
- zeros_like: zeros_like[TArray, TDtype, TDevice]¶
Returns a new array filled with zeros and having the same
shapeas an input arrayx.- Parameters:
x (array) – input array from which to derive the output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be inferred fromx. Default:None.device (Optional[device]) – device on which to place the created array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the same shape as
xand filled with zeros.- Return type:
array
- class array_api._2025_12.ArrayNamespaceFull(*args, **kwargs)[source]¶
Bases:
ArrayNamespace,Protocol,Generic- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- fft: FftNamespace[TArray, TDtype, TDevice]¶
- linalg: LinalgNamespace[TArray, TDtype]¶
- class array_api._2025_12.Capabilities¶
Bases:
TypedDict
- class array_api._2025_12.DataTypes[source]¶
Bases:
TypedDict- bool: Any¶
- complex128: Any¶
- complex64: Any¶
- float32: Any¶
- float64: Any¶
- int16: Any¶
- int32: Any¶
- int64: Any¶
- int8: Any¶
- uint16: Any¶
- uint32: Any¶
- uint64: Any¶
- uint8: Any¶
- class array_api._2025_12.FftNamespace(*args, **kwargs)[source]¶
Bases:
Protocol,Generic- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- fft: fft¶
Computes the one-dimensional discrete Fourier transform.
Note
Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
ifft(fft(x)) == x), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode).- Parameters:
x (array) – input array. Should have a complex floating-point data type.
n (Optional[int]) –
number of elements over which to compute the transform along the axis (dimension) specified by
axis. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal toM.If
nis greater thanM, the axis specified byaxismust be zero-padded to sizen.If
nis less thanM, the axis specified byaxismust be trimmed to sizen.If
nequalsM, all elements along the axis specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have the same data type asxand must have the same shape asx, except for the axis specified byaxiswhich must have sizen.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array.
- fftfreq: fftfreq¶
Computes the discrete Fourier transform sample frequencies.
For a Fourier transform of length
nand length unit ofd, the frequencies are described as:f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd
- Parameters:
n (int) – window length.
d (float) – sample spacing between individual samples of the Fourier transform input. Default:
1.0.dtype (Optional[dtype]) – output array data type. Must be a real-valued floating-point data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array of shape
(n,)containing the sample frequencies.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the output array have the default real-valued floating-point data type.
Changed in version 2024.12: Added
dtypekeyword argument support.
- fftn: fftn¶
Computes the n-dimensional discrete Fourier transform.
Note
Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
ifftn(fftn(x)) == x), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode).- Parameters:
x (array) – input array. Should have a complex floating-point data type.
s (Optional[Sequence[int]]) –
number of elements over which to compute the transform along the axes (dimensions) specified by
axes. Letibe the index of then-th axis specified byaxes(i.e.,i = axes[n]) andM[i]be the size of the input array along axisi. WhensisNone, the function must setsequal to a sequence of integers such thats[i]equalsM[i]for alli.If
s[i]is greater thanM[i], axisimust be zero-padded to sizes[i].If
s[i]is less thanM[i], axisimust be trimmed to sizes[i].If
s[i]equalsM[i]or-1, all elements along axisimust be used when computing the transform.
If
sis notNone,axesmust not beNone. Default:None.axes (Optional[Sequence[int]]) –
axes (dimensions) over which to compute the transform. A valid axis in
axesmust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension).If
sis provided, the correspondingaxesto be transformed must also be provided. IfaxesisNone, the function must compute the transform over all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
where
n = prod(s)is the logical FFT size.Default:
'backward'.
- Returns:
out – an array transformed along the axes (dimensions) specified by
axes. The returned array must have the same data type asxand must have the same shape asx, except for the axes specified byaxeswhich must have sizes[i].- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array.
- fftshift: fftshift¶
Shifts the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes (dimensions) specified by
axes.Note
out[0]is the Nyquist component only if the length of the input is even.- Parameters:
x (array) – input array. Should have a floating-point data type.
axes (Optional[Union[int, Sequence[int]]]) –
axes over which to shift. If
None, the function must shift all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.
- Returns:
out – the shifted array. The returned array must have the same data type and shape as
x.- Return type:
array
Notes
Added in version 2022.12.
- hfft: hfft¶
Computes the one-dimensional discrete Fourier transform of a signal with Hermitian symmetry.
- Parameters:
x (array) – input array. Should have a complex floating-point data type.
n (Optional[int]) –
number of elements along the transformed axis (dimension) specified by
axisin the output array. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal to2*(M-1).If
n//2+1is greater thanM, the axis of the input array specified byaxismust be zero-padded to lengthn//2+1.If
n//2+1is less thanM, the axis of the input array specified byaxismust be trimmed to sizen//2+1.If
n//2+1equalsM, all elements along the axis of the input array specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type). The returned array must have the same shape asx, except for the axis specified byaxiswhich must have sizen.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array to have a complex floating-point data type and required that the output array have a real-valued data type having the same precision as the input array.
- ifft: ifft¶
Computes the one-dimensional inverse discrete Fourier transform.
Note
Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
ifft(fft(x)) == x), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode).- Parameters:
x (array) – input array. Should have a complex floating-point data type.
n (Optional[int]) –
number of elements over which to compute the transform along the axis (dimension) specified by
axis. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal toM.If
nis greater thanM, the axis specified byaxismust be zero-padded to sizen.If
nis less thanM, the axis specified byaxismust be trimmed to sizen.If
nequalsM, all elements along the axis specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have the same data type asxand must have the same shape asx, except for the axis specified byaxiswhich must have sizen.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array.
- ifftn: ifftn¶
Computes the n-dimensional inverse discrete Fourier transform.
Note
Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
ifftn(fftn(x)) == x), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode).- Parameters:
x (array) – input array. Should have a complex floating-point data type.
s (Optional[Sequence[int]]) –
number of elements over which to compute the transform along the axes (dimensions) specified by
axes. Letibe the index of then-th axis specified byaxes(i.e.,i = axes[n]) andM[i]be the size of the input array along axisi. WhensisNone, the function must setsequal to a sequence of integers such thats[i]equalsM[i]for alli.If
s[i]is greater thanM[i], axisimust be zero-padded to sizes[i].If
s[i]is less thanM[i], axisimust be trimmed to sizes[i].If
s[i]equalsM[i]or-1, all elements along axisimust be used when computing the transform.
If
sis notNone,axesmust not beNone. Default:None.axes (Optional[Sequence[int]]) –
axes (dimensions) over which to compute the transform. A valid axis in
axesmust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension).If
sis provided, the correspondingaxesto be transformed must also be provided. IfaxesisNone, the function must compute the transform over all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.norm (Literal['backward', 'ortho', 'forward']) –
specify the normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
where
n = prod(s)is the logical FFT size.Default:
'backward'.
- Returns:
out – an array transformed along the axes (dimensions) specified by
axes. The returned array must have the same data type asxand must have the same shape asx, except for the axes specified byaxeswhich must have sizes[i].- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array.
- ifftshift: ifftshift¶
Inverse of
fftshift.Note
Although identical for even-length
x,fftshiftandifftshiftdiffer by one sample for odd-lengthx.- Parameters:
x (array) – input array. Should have a floating-point data type.
axes (Optional[Union[int, Sequence[int]]]) –
axes over which to perform the inverse shift. If
None, the function must shift all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.
- Returns:
out – the shifted array. The returned array must have the same data type and shape as
x.- Return type:
array
Notes
Added in version 2022.12.
- ihfft: ihfft¶
Computes the one-dimensional inverse discrete Fourier transform of a signal with Hermitian symmetry.
- Parameters:
x (array) – input array. Must have a real-valued floating-point data type.
n (Optional[int]) –
number of elements over which to compute the transform along the axis (dimension) specified by
axis. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal toM.If
nis greater thanM, the axis specified byaxismust be zero-padded to sizen.If
nis less thanM, the axis specified byaxismust be trimmed to sizen.If
nequalsM, all elements along the axis specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have a complex floating-point data type whose precision matches the precision ofx(e.g., ifxisfloat64, then the returned array must have acomplex128data type). The returned array must have the same shape asx, except for the axis specified byaxiswhich must have sizen//2 + 1.- Return type:
array
Notes
Added in version 2022.12.
- irfft: irfft¶
Computes the one-dimensional inverse of
rfftfor complex-valued input.Note
Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
irfft(rfft(x)) == x), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms.- Parameters:
x (array) – input array. Should have a complex floating-point data type.
n (Optional[int]) –
number of elements along the transformed axis (dimension) specified by
axisin the output array. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal to2*(M-1).If
n//2+1is greater thanM, the axis of the input array specified byaxismust be zero-padded to sizen//2+1.If
n//2+1is less thanM, the axis of the input array specified byaxismust be trimmed to sizen//2+1.If
n//2+1equalsM, all elements along the axis of the input array specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type). The returned array must have the same shape asx, except for the axis specified byaxiswhich must have sizen.- Return type:
array
Notes
In order to return an array having an odd number of elements along the transformed axis, the function must be provided an odd integer for
n.
Added in version 2022.12.
Changed in version 2023.12: Required the output array have a real-valued floating-point data type having the same precision as the input array.
- irfftn: irfftn¶
Computes the n-dimensional inverse of
rfftnfor complex-valued input.Note
Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
irfftn(rfftn(x)) == x), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes.- Parameters:
x (array) – input array. Should have a complex floating-point data type.
s (Optional[Sequence[int]]) –
number of elements along the transformed axes (dimensions) specified by
axesin the output array. Letibe the index of then-th axis specified byaxes(i.e.,i = axes[n]) andM[i]be the size of the input array along axisi. WhensisNone, the function must setsequal to a sequence of integers such thats[i]equalsM[i]for alli, except for the last transformed axis in whichs[i]equals2*(M[i]-1). For eachi, letnequals[i], except for the last transformed axis in whichnequalss[i]//2+1.If
nis greater thanM[i], axisiof the input array must be zero-padded to sizen.If
nis less thanM[i], axisiof the input array must be trimmed to sizen.If
nequalsM[i]or-1, all elements along axisiof the input array must be used when computing the transform.
If
sis notNone,axesmust not beNone. Default:None.axes (Optional[Sequence[int]]) –
axes (dimensions) over which to compute the transform. A valid axis in
axesmust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension).If
sis provided, the correspondingaxesto be transformed must also be provided. IfaxesisNone, the function must compute the transform over all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
where
n = prod(s)is the logical FFT size.Default:
'backward'.
- Returns:
out – an array transformed along the axes (dimension) specified by
axes. The returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type). The returned array must have the same shape asx, except for the transformed axes which must have sizes[i].- Return type:
array
Notes
In order to return an array having an odd number of elements along the last transformed axis, the function must be provided an odd integer for
s[-1].
Added in version 2022.12.
Changed in version 2023.12: Required the output array have a real-valued floating-point data type having the same precision as the input array.
- rfft: rfft¶
Computes the one-dimensional discrete Fourier transform for real-valued input.
Note
Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
irfft(rfft(x)) == x), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms.- Parameters:
x (array) – input array. Must have a real-valued floating-point data type.
n (Optional[int]) –
number of elements over which to compute the transform along the axis (dimension) specified by
axis. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal toM.If
nis greater thanM, the axis specified byaxismust be zero-padded to sizen.If
nis less thanM, the axis specified byaxismust be trimmed to sizen.If
nequalsM, all elements along the axis specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have a complex floating-point data type whose precision matches the precision ofx(e.g., ifxisfloat64, then the returned array must have acomplex128data type). The returned array must have the same shape asx, except for the axis specified byaxiswhich must have sizen//2 + 1.- Return type:
array
Notes
Added in version 2022.12.
- rfftfreq: rfftfreq¶
Computes the discrete Fourier transform sample frequencies (for
rfftandirfft).For a Fourier transform of length
nand length unit ofd, the frequencies are described as:f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd
The Nyquist frequency component is considered to be positive.
- Parameters:
n (int) – window length.
d (float) – sample spacing between individual samples of the Fourier transform input. Default:
1.0.dtype (Optional[dtype]) – output array data type. Must be a real-valued floating-point data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array of shape
(n//2+1,)containing the sample frequencies.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the output array have the default real-valued floating-point data type.
Changed in version 2024.12: Added
dtypekeyword argument support.
- rfftn: rfftn¶
Computes the n-dimensional discrete Fourier transform for real-valued input.
Note
Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
irfftn(rfftn(x)) == x), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes.- Parameters:
x (array) – input array. Must have a real-valued floating-point data type.
s (Optional[Sequence[int]]) –
number of elements over which to compute the transform along axes (dimensions) specified by
axes. Letibe the index of then-th axis specified byaxes(i.e.,i = axes[n]) andM[i]be the size of the input array along axisi. WhensisNone, the function must setsequal to a sequence of integers such thats[i]equalsM[i]for alli.If
s[i]is greater thanM[i], axisimust be zero-padded to sizes[i].If
s[i]is less thanM[i], axisimust be trimmed to sizes[i].If
s[i]equalsM[i]or-1, all elements along axisimust be used when computing the transform.
If
sis notNone,axesmust not beNone. Default:None.axes (Optional[Sequence[int]]) –
axes (dimensions) over which to compute the transform. A valid axis in
axesmust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension).If
sis provided, the correspondingaxesto be transformed must also be provided. IfaxesisNone, the function must compute the transform over all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
where
n = prod(s), the logical FFT size.Default:
'backward'.
- Returns:
out – an array transformed along the axes (dimension) specified by
axes. The returned array must have a complex floating-point data type whose precision matches the precision ofx(e.g., ifxisfloat64, then the returned array must have acomplex128data type). The returned array must have the same shape asx, except for the last transformed axis which must have sizes[-1]//2 + 1and the remaining transformed axes which must have sizes[i].- Return type:
array
Notes
Added in version 2022.12.
- class array_api._2025_12.Info(*args, **kwargs)[source]¶
Bases:
Protocol,GenericNamespace returned by __array_namespace_info__.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- capabilities() Capabilities[source]¶
- default_dtypes(*, device: TDevice | None) DefaultDataTypes[source]¶
- class array_api._2025_12.LinalgNamespace(*args, **kwargs)[source]¶
Bases:
Protocol,Generic- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- cholesky: cholesky¶
Returns the lower (upper) Cholesky decomposition of a complex Hermitian or real symmetric positive-definite matrix
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The lower Cholesky decomposition of a complex Hermitian or real symmetric positive-definite matrix \(x \in\ \mathbb{K}^{n \times n}\) is defined as
\[x = LL^{H} \qquad \text{L $\in\ \mathbb{K}^{n \times n}$}\]where \(L\) is a lower triangular matrix and \(L^{H}\) is the conjugate transpose when \(L\) is complex-valued and the transpose when \(L\) is real-valued.
The upper Cholesky decomposition is defined similarly
\[x = U^{H}U \qquad \text{U $\in\ \mathbb{K}^{n \times n}$}\]where \(U\) is an upper triangular matrix.
When
xis a stack of matrices, the function must compute the Cholesky decomposition for each matrix in the stack.Note
Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined.
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type.upper (bool) – If
True, the result must be the upper-triangular Cholesky factor \(U\). IfFalse, the result must be the lower-triangular Cholesky factor \(L\). Default:False.
- Returns:
out – an array containing the Cholesky factors for each square matrix. If
upperisFalse, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by type-promotion and must have the same shape asx.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- cross: cross¶
Returns the cross product of 3-element vectors.
If
x1and/orx2are multi-dimensional arrays (i.e., the broadcasted result has a rank greater than1), then the cross-product of each pair of corresponding 3-element vectors is independently computed.- Parameters:
x1 (array) – first input array. Must have a numeric data type. The size of the axis over which the cross product is to be computed must be equal to 3.
x2 (array) –
second input array. Must be broadcast compatible with
x1along all axes other than the axis along which the cross-product is computed (see broadcasting). The size of the axis over which the cross product is to be computed must be equal to 3. Must have a numeric data type.Note
The compute axis (dimension) must not be broadcasted.
axis (int) – the axis (dimension) of
x1andx2containing the vectors for which to compute the cross product. Should be an integer on the interval[-N, -1], whereNismin(x1.ndim, x2.ndim). The function must determine the axis along which to compute the cross product by counting backward from the last dimension (where-1refers to the last dimension). By default, the function must compute the cross product over the last axis. Default:-1.
- Returns:
out – an array containing the cross products. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
Raises
if the size of the axis over which to compute the cross product is not equal to
3(before broadcasting) for bothx1andx2.
Changed in version 2022.12: Added support for broadcasting.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Restricted broadcasting to only non-compute axes and required that
axisbe a negative integer.
- det: det¶
Returns the determinant of a square matrix (or a stack of square matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – if
xis a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type asx.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- diagonal: diagonal¶
Returns the specified diagonals of a matrix (or a stack of matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices.offset (int) –
offset specifying the off-diagonal relative to the main diagonal.
offset = 0: the main diagonal.offset > 0: off-diagonal above the main diagonal.offset < 0: off-diagonal below the main diagonal.
Default: 0.
- Returns:
out – an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as
x.- Return type:
array
- eig: eig¶
Returns eigenvalues and eigenvectors of a real or complex matrix (or stack of matrices)
x.Let \(\mathbb{K}\) be the union of the set of real numbers \(\mathbb{R}\) and the set of complex numbers, \(\mathbb{C}\).
A real or complex value \(lambda \in \mathbb{K}\) is an eigenvalue of a real or complex matrix \(x \in \mathbb{K}^{n \times n}\) if there exists a real or complex vector \(v \in \mathbb{K}^{n}\), such that
\[x v = \lambda v\]Then, \(v\) is referred to as an eigenvector of \(x\), corresponding to the eigenvalue \(\lambda\).
A general matrix \(x \in \mathbb{K}^{n \times n}\)
has \(n\) eigenvalues, which are defined as the roots (counted with multiplicity) of the polynomial \(p\) of degree \(n\) given by
\[p(\lambda) = \operatorname{det}(x - \lambda I_n)\]does not in general have \(n\) linearly independent eigenvectors if it has eigenvalues with multiplicity larger than one.
Note
The eigenvalues of a non-symmetric real matrix are in general complex: for :math:x in mathbb{R}^{n times n}`, the eigenvalues, \(\lambda \in \mathbb{C}\), may or may not reside on the real axis of the complex plane.
Warning
The eigenvectors of a general matrix are not unique and are not continuous with respect to
x. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors.For eigenvalues of multiplity \(s=1\), the non-uniqueness stems from the fact that multiplying an eigenvector by \(-1\) when
xis real-valued and by \(e^{\phi j}\) (\(\phi \in \mathbb{R}\)) whenxis complex produces another set of valid eigenvectors.For eigenvalues of multiplity \(s > 1\), the \(s\) computed eigenvectors may be repeated or have entries differ by an order of machine epsilon for the data type of \(x\).
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – a namedtuple (
eigenvalues,eigenvectors) whosefirst element must have the field name
eigenvalues(corresponding to \(\lambda\) above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape(..., M)and must have a complex floating-point array data type having the same precision as that ofx(e.g., ifxhas afloat32data type,eigenvaluesmust have thecomplex64data type; ifxhas afloat64data type,eigenvalueshave thecomplex128data type).second element must have the field name
eigenvectors(corresponding to \(v\) above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape(..., M, M)and must have the same data type aseigenvalues.
- Return type:
Tuple[array, array]
Notes
Eigenvalue sort order is left unspecified and is thus implementation-dependent.
Note
For real symmetric or complex Hermitian matrices, prefer using the
eighroutine.Added in version 2025.12.
- eigh: eigh¶
Returns an eigenvalue decomposition of a complex Hermitian or real symmetric matrix (or a stack of matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The eigenvalue decomposition of a complex Hermitian or real symmetric matrix \(x \in\ \mathbb{K}^{n \times n}\) is defined as
\[x = Q \Lambda Q^H\]with \(Q \in \mathbb{K}^{n \times n}\) and \(\Lambda \in \mathbb{R}^n\) and where \(Q^H\) is the conjugate transpose when \(Q\) is complex and the transpose when \(Q\) is real-valued and \(\Lambda\) is a diagonal matrix whose diagonal elements are the corresponding eigenvalues. When
xis real-valued, \(Q\) is orthogonal, and, whenxis complex, \(Q\) is unitary.Note
The eigenvalues of a complex Hermitian or real symmetric matrix are always real.
Warning
The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to
x. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors.Non-uniqueness stems from the fact that multiplying an eigenvector by \(-1\) when
xis real-valued and by \(e^{\phi j}\) (\(\phi \in \mathbb{R}\)) whenxis complex produces another set of valid eigenvectors.Note
Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined.
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – a namedtuple (
eigenvalues,eigenvectors) whosefirst element must have the field name
eigenvalues(corresponding to \(\operatorname{diag}\Lambda\) above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape(..., M)and must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, theneigenvaluesmust befloat64).second element must have the field name
eigenvectors(corresponding to \(Q\) above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape(..., M, M)and must have the same data type asx.
- Return type:
Tuple[array, array]
Notes
Note
Eigenvalue sort order is left unspecified and is thus implementation-dependent.
Changed in version 2022.12: Added complex data type support.
- eigvals: eigvals¶
Returns the eigenvalues of a real or complex matrix (or a stack of matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the union of the set of real numbers \(\mathbb{R}\) and the set of complex numbers, \(\mathbb{C}\); ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The eigenvalues of a real or complex matrix \(x \in\ \mathbb{K}^{n \times n}\) are defined as the roots (counted with multiplicity) of the polynomial \(p\) of degree \(n\) given by
\[p(\lambda) = \operatorname{det}(x - \lambda I_n)\]where \(\lambda \in \mathbb{K}\) and where \(I_n\) is the n-dimensional identity matrix.
Note
The eigenvalues of a non-symmetric real matrix are in general complex: for :math:x in mathbb{R}^{n times n}`, the eigenvalues \(\lambda \in \mathbb{C}\), may or may not reside on the real axis of the complex plane.
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – an array containing the computed eigenvalues. The returned array must have shape
(..., M)and have a complex floating-point array data type having the same precision as that ofx(e.g., ifxhas afloat32data type, the array must have thecomplex64data type; ifxhas afloat64data type, the array has thecomplex128data type).- Return type:
array
Notes
Eigenvalue sort order is left unspecified and is thus implementation-dependent.
Added in version 2025.12.
- eigvalsh: eigvalsh¶
Returns the eigenvalues of a complex Hermitian or real symmetric matrix (or a stack of matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The eigenvalues of a complex Hermitian or real symmetric matrix \(x \in\ \mathbb{K}^{n \times n}\) are defined as the roots (counted with multiplicity) of the polynomial \(p\) of degree \(n\) given by
\[p(\lambda) = \operatorname{det}(x - \lambda I_n)\]where \(\lambda \in \mathbb{R}\) and where \(I_n\) is the n-dimensional identity matrix.
Note
The eigenvalues of a complex Hermitian or real symmetric matrix are always real.
Note
Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined.
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – an array containing the computed eigenvalues. The returned array must have shape
(..., M)and have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then must have afloat64data type).- Return type:
array
Notes
Note
Eigenvalue sort order is left unspecified and is thus implementation-dependent.
Changed in version 2022.12: Added complex data type support.
- inv: inv¶
Returns the multiplicative inverse of a square matrix (or a stack of square matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The inverse matrix \(x^{-1} \in\ \mathbb{K}^{n \times n}\) of a square matrix \(x \in\ \mathbb{K}^{n \times n}\) is defined as
\[x^{-1}x = xx^{-1} = I_n\]where \(I_n\) is the n-dimensional identity matrix.
The inverse matrix exists if and only if
xis invertible. Whenxis invertible, the inverse is unique.When
xis a stack of matrices, the function must compute the inverse for each matrix in the stack.- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by type-promotion and must have the same shape as
x.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- matrix_norm: matrix_norm¶
Computes the matrix norm of a matrix (or a stack of matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices. Should have a floating-point data type.keepdims (bool) – If
True, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the last two axes (dimensions) must not be included in the result. Default:False.ord (Optional[Union[int, float, Literal[inf, -inf, 'fro', 'nuc']]]) –
order of the norm. The following mathematical norms must be supported:
ord
description
’fro’
Frobenius norm
’nuc’
nuclear norm
1
max(sum(abs(x), axis=0))
2
largest singular value
inf
max(sum(abs(x), axis=1))
The following non-mathematical “norms” must be supported:
ord
description
-1
min(sum(abs(x), axis=0))
-2
smallest singular value
-inf
min(sum(abs(x), axis=1))
If
ord=1, the norm corresponds to the induced matrix norm wherep=1(i.e., the maximum absolute value column sum).If
ord=2, the norm corresponds to the induced matrix norm wherep=inf(i.e., the maximum absolute value row sum).If
ord=inf, the norm corresponds to the induced matrix norm wherep=2(i.e., the largest singular value).Default:
'fro'.
- Returns:
out – an array containing the norms for each
MxNmatrix. IfkeepdimsisFalse, the returned array must have a rank which is two less than the rank ofx. Ifxhas a real-valued data type, the returned array must have a real-valued floating-point data type determined by type-promotion. Ifxhas a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- matrix_power: matrix_power¶
Raises a square matrix (or a stack of square matrices)
xto an integer powern.- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.n (int) – integer exponent.
- Returns:
out – if
nis equal to zero, an array containing the identity matrix for each square matrix. Ifnis less than zero, an array containing the inverse of each square matrix raised to the absolute value ofn, provided that each square matrix is invertible. Ifnis greater than zero, an array containing the result of raising each square matrix to the powern. The returned array must have the same shape asxand a floating-point data type determined by type-promotion.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- matrix_rank: matrix_rank¶
Returns the rank (i.e., number of non-zero singular values) of a matrix (or a stack of matrices).
When
xis a stack of matrices, the function must compute the number of non-zero singular values for each matrix in the stack.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices. Should have a floating-point data type.rtol (Optional[Union[float, array]]) – relative tolerance for small singular values. Singular values approximately less than or equal to
rtol * largest_singular_valueare set to zero. If afloat, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by type-promotion (as applied tox) and must be broadcast against each matrix. If anarray, must have a real-valued floating-point data type and must be compatible withshape(x)[:-2](see broadcasting). IfNone, the default value ismax(M, N) * eps, whereepsmust be the machine epsilon associated with the real-valued floating-point data type determined by type-promotion (as applied tox). Default:None.
- Returns:
out – an array containing the ranks. The returned array must have the default integer data type and must have shape
(...)(i.e., must have a shape equal toshape(x)[:-2]).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- matrix_transpose: matrix_transpose¶
Alias for
matrix_transpose().
- outer: outer¶
Returns the outer product of two vectors
x1andx2.- Parameters:
x1 (array) – first one-dimensional input array of size
N. Must have a numeric data type.x2 (array) – second one-dimensional input array of size
M. Must have a numeric data type.
- Returns:
out – a two-dimensional array containing the outer product and whose shape is
(N, M). The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- pinv: pinv¶
Returns the (Moore-Penrose) pseudo-inverse of a matrix (or a stack of matrices)
x.The pseudo-inverse of a matrix \(A\), denoted \(A^{+}\), is defined as the matrix that “solves” the least-squares problem \(Ax = b\) (i.e., if \(\overline{x}\) is a solution, then \(A^{+}\) is the matrix such that \(\overline{x} = A^{+}b\)).
While the pseudo-inverse can be defined algebraically, one can understand the pseudo-inverse via singular value decomposition (SVD). Namely, if
\[A = U \Sigma V^H\]is a singular decomposition of \(A\), then
\[A^{+} = U \Sigma^{+} V^H\]where \(U\) and \(V^H\) are orthogonal matrices, \(\Sigma\) is a diagonal matrix consisting of \(A\)’s singular values, and \(\Sigma^{+}\) is then a diagonal matrix consisting of the reciprocals of \(A\)’s singular values, leaving zeros in place. During numerical computation, only elements larger than a small tolerance are considered nonzero, and all others replaced by zeros.
When
xis a stack of matrices, the function must compute the pseudo-inverse for each matrix in the stack.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices. Should have a floating-point data type.rtol (Optional[Union[float, array]]) – relative tolerance for small singular values. Singular values approximately less than or equal to
rtol * largest_singular_valueare set to zero. If afloat, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by type-promotion (as applied tox) and must be broadcast against each matrix. If anarray, must have a real-valued floating-point data type and must be compatible withshape(x)[:-2](see broadcasting). IfNone, the default value ismax(M, N) * eps, whereepsmust be the machine epsilon associated with the real-valued floating-point data type determined by type-promotion (as applied tox). Default:None.
- Returns:
out – an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by type-promotion and must have shape
(..., N, M)(i.e., must have the same shape asx, except the innermost two dimensions must be transposed).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- qr: qr¶
Returns the QR decomposition of a full column rank matrix (or a stack of matrices).
If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The complete QR decomposition of a matrix \(x \in\ \mathbb{K}^{n \times n}\) is defined as
\[x = QR\]where \(Q \in\ \mathbb{K}^{m \times m}\) is orthogonal when
xis real-valued and unitary whenxis complex-valued and where \(R \in\ \mathbb{K}^{m \times n}\) is an upper triangular matrix with real diagonal (even whenxis complex-valued).When \(m \gt n\) (tall matrix), as \(R\) is upper triangular, the last \(m - n\) rows are zero. In this case, the last \(m - n\) columns of \(Q\) can be dropped to form the reduced QR decomposition.
\[x = QR\]where \(Q \in\ \mathbb{K}^{m \times n}\) and \(R \in\ \mathbb{K}^{n \times n}\).
The reduced QR decomposition equals with the complete QR decomposition when \(n \geq m\) (wide matrix).
When
xis a stack of matrices, the function must compute the QR decomposition for each matrix in the stack.Note
Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined.
Warning
The elements in the diagonal of \(R\) are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of \(R\), and different libraries or inputs on different devices may produce different valid decompositions.
Warning
The QR decomposition is only well-defined if the first
k = min(m,n)columns of every matrix inxare linearly independent.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices of rankN. Should have a floating-point data type.mode (Literal['reduced', 'complete']) –
decomposition mode. Should be one of the following modes:
'reduced': compute only the leadingKcolumns ofq, such thatqandrhave dimensions(..., M, K)and(..., K, N), respectively, and whereK = min(M, N).'complete': computeqandrwith dimensions(..., M, M)and(..., M, N), respectively.
Default:
'reduced'.
- Returns:
out – a namedtuple
(Q, R)whosefirst element must have the field name
Qand must be an array whose shape depends on the value ofmodeand contain matrices with orthonormal columns. Ifmodeis'complete', the array must have shape(..., M, M). Ifmodeis'reduced', the array must have shape(..., M, K), whereK = min(M, N). The firstx.ndim-2dimensions must have the same size as those of the input arrayx.second element must have the field name
Rand must be an array whose shape depends on the value ofmodeand contain upper-triangular matrices. Ifmodeis'complete', the array must have shape(..., M, N). Ifmodeis'reduced', the array must have shape(..., K, N), whereK = min(M, N). The firstx.ndim-2dimensions must have the same size as those of the inputx.
Each returned array must have a floating-point data type determined by type-promotion.
- Return type:
Tuple[array, array]
Notes
Changed in version 2022.12: Added complex data type support.
- slogdet: slogdet¶
Returns the sign and the natural logarithm of the absolute value of the determinant of a square matrix (or a stack of square matrices)
x.Note
The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling
detmay overflow or underflow.The sign of the determinant is given by
\[\begin{split}\operatorname{sign}(\det x) = \begin{cases} 0 & \textrm{if } \det x = 0 \\ \frac{\det x}{|\det x|} & \textrm{otherwise} \end{cases}\end{split}\]where \(|\det x|\) is the absolute value of the determinant of
x.When
xis a stack of matrices, the function must compute the sign and natural logarithm of the absolute value of the determinant for each matrix in the stack.Special Cases
For real-valued floating-point operands,
If the determinant is zero, the
signshould be0andlogabsdetshould be-infinity.
For complex floating-point operands,
If the determinant is
0 + 0j, thesignshould be0 + 0jandlogabsdetshould be-infinity + 0j.
Note
Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from
-infinity(or-infinity + 0j). In all cases, the determinant should be equal tosign * exp(logabsdet)(although, again, the result may be subject to numerical precision errors).- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – a namedtuple (
sign,logabsdet) whosefirst element must have the field name
signand must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type asx.second element must have the field name
logabsdetand must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. Ifxis real-valued, the returned array must have a real-valued floating-point data type determined by type-promotion. Ifxis complex, the returned array must have a real-valued floating-point data type having the same precision asx(e.g., ifxiscomplex64,logabsdetmust have afloat32data type).
Each returned array must have shape
shape(x)[:-2].- Return type:
Tuple[array, array]
Notes
Changed in version 2022.12: Added complex data type support.
- solve: solve¶
Returns the solution of a square system of linear equations with a unique solution.
Let
x1equal \(A\) andx2equal \(B\). If the promoted data type ofx1andx2is real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, if the promoted data type ofx1andx2is complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).This function computes the solution \(X \in\ \mathbb{K}^{m \times k}\) of the linear system associated to \(A \in\ \mathbb{K}^{m \times m}\) and \(B \in\ \mathbb{K}^{m \times k}\) and is defined as
\[AX = B\]This system of linear equations has a unique solution if and only if \(A\) is invertible.
Note
Whether an array library explicitly checks whether
x1is invertible is implementation-defined.When
x1and/orx2is a stack of matrices, the function must compute a solution for each matrix in the stack.- Parameters:
x1 (array) – coefficient array
Ahaving shape(..., M, M)and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type.x2 (array) – ordinate (or “dependent variable”) array
B. Ifx2has shape(M,),x2is equivalent to an array having shape(..., M, 1). Ifx2has shape(..., M, K), each columnkdefines a set of ordinate values for which to compute a solution, andshape(x2)[:-2]must be compatible withshape(x1)[:-2](see broadcasting). Should have a floating-point data type.
- Returns:
out – an array containing the solution to the system
AX = Bfor each square matrix. Ifx2has shape(M,), the returned array must have shape equal toshape(x1)[:-2] + shape(x2)[-1:]. Otherwise, ifx2has shape(..., M, K)`, the returned array must have shape equal to(..., M, K), where...refers to the result of broadcastingshape(x1)[:-2]andshape(x2)[:-2]. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Clarified broadcasting semantics and the shape of the output array.
- svd: svd¶
Returns a singular value decomposition (SVD) of a matrix (or a stack of matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The full singular value decomposition of an \(m \times n\) matrix \(x \in\ \mathbb{K}^{m \times n}\) is a factorization of the form
\[x = U \Sigma V^H\]where \(U \in\ \mathbb{K}^{m \times m}\), \(\Sigma \in\ \mathbb{K}^{m \times\ n}\), \(\operatorname{diag}(\Sigma) \in\ \mathbb{R}^{k}\) with \(k = \operatorname{min}(m, n)\), \(V^H \in\ \mathbb{K}^{n \times n}\), and where \(V^H\) is the conjugate transpose when \(V\) is complex and the transpose when \(V\) is real-valued. When
xis real-valued, \(U\), \(V\) (and thus \(V^H\)) are orthogonal, and, whenxis complex, \(U\), \(V\) (and thus \(V^H\)) are unitary.When \(m \gt n\) (tall matrix), we can drop the last \(m - n\) columns of \(U\) to form the reduced SVD
\[x = U \Sigma V^H\]where \(U \in\ \mathbb{K}^{m \times k}\), \(\Sigma \in\ \mathbb{K}^{k \times\ k}\), \(\operatorname{diag}(\Sigma) \in\ \mathbb{R}^{k}\), and \(V^H \in\ \mathbb{K}^{k \times n}\). In this case, \(U\) and \(V\) have orthonormal columns.
Similarly, when \(n \gt m\) (wide matrix), we can drop the last \(n - m\) columns of \(V\) to also form a reduced SVD.
This function returns the decomposition \(U\), \(S\), and \(V^H\), where \(S = \operatorname{diag}(\Sigma)\).
When
xis a stack of matrices, the function must compute the singular value decomposition for each matrix in the stack.Warning
The returned arrays \(U\) and \(V\) are neither unique nor continuous with respect to
x. Because \(U\) and \(V\) are not unique, different hardware and software may compute different singular vectors.Non-uniqueness stems from the fact that multiplying any pair of singular vectors \(u_k\), \(v_k\) by \(-1\) when
xis real-valued and by \(e^{\phi j}\) (\(\phi \in \mathbb{R}\)) whenxis complex produces another two valid singular vectors of the matrix.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type.full_matrices (bool) – If
True, compute full-sizedUandVh, such thatUhas shape(..., M, M)andVhhas shape(..., N, N). IfFalse, compute on the leadingKsingular vectors, such thatUhas shape(..., M, K)andVhhas shape(..., K, N)and whereK = min(M, N). Default:True.
- Returns:
out – a namedtuple
(U, S, Vh)whosefirst element must have the field name
Uand must be an array whose shape depends on the value offull_matricesand contain matrices with orthonormal columns (i.e., the columns are left singular vectors). Iffull_matricesisTrue, the array must have shape(..., M, M). Iffull_matricesisFalse, the array must have shape(..., M, K), whereK = min(M, N). The firstx.ndim-2dimensions must have the same shape as those of the inputx. Must have the same data type asx.second element must have the field name
Sand must be an array with shape(..., K)that contains the vector(s) of singular values of lengthK, whereK = min(M, N). For each vector, the singular values must be sorted in descending order by magnitude, such thats[..., 0]is the largest value,s[..., 1]is the second largest value, et cetera. The firstx.ndim-2dimensions must have the same shape as those of the inputx. Must have a real-valued floating-point data type having the same precision asx(e.g., ifxiscomplex64,Smust have afloat32data type).third element must have the field name
Vhand must be an array whose shape depends on the value offull_matricesand contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). Iffull_matricesisTrue, the array must have shape(..., N, N). Iffull_matricesisFalse, the array must have shape(..., K, N)whereK = min(M, N). The firstx.ndim-2dimensions must have the same shape as those of the inputx. Must have the same data type asx.
- Return type:
Tuple[array, array, array]
Notes
Changed in version 2022.12: Added complex data type support.
- svdvals: svdvals¶
Returns the singular values of a matrix (or a stack of matrices)
x.When
xis a stack of matrices, the function must compute the singular values for each matrix in the stack.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type.- Returns:
out – an array with shape
(..., K)that contains the vector(s) of singular values of lengthK, whereK = min(M, N). For each vector, the singular values must be sorted in descending order by magnitude, such thats[..., 0]is the largest value,s[..., 1]is the second largest value, et cetera. The firstx.ndim-2dimensions must have the same shape as those of the inputx. The returned array must have a real-valued floating-point data type having the same precision asx(e.g., ifxiscomplex64, the returned array must have afloat32data type).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- trace: trace¶
Returns the sum along the specified diagonals of a matrix (or a stack of matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices. Should have a numeric data type.offset (int) –
offset specifying the off-diagonal relative to the main diagonal.
offset = 0: the main diagonal.offset > 0: off-diagonal above the main diagonal.offset < 0: off-diagonal below the main diagonal.
Default:
0.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the sum (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.
- Returns:
out – an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if
xhas rankkand shape(I, J, K, ..., L, M, N), then an output array has rankk-2and shape(I, J, K, ..., L)whereout[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :])
The returned array must have a data type as described by the
dtypeparameter above.- Return type:
array
Notes
Special Cases
Let
Nequal the number of elements over which to compute the sum.If
Nis0, the sum is0(i.e., the empty sum).
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
add().Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array.
- vector_norm: vector_norm¶
Computes the vector norm of a vector (or batch of vectors)
x.- Parameters:
x (array) – input array. Should have a floating-point data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – If an integer,
axisspecifies the axis (dimension) along which to compute vector norms. If an n-tuple,axisspecifies the axes (dimensions) along which to compute batched vector norms. IfNone, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default:None.keepdims (bool) – If
True, the axes (dimensions) specified byaxismust be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the axes (dimensions) specified byaxismust not be included in the result. Default:False.ord (Union[int, float, Literal[inf, -inf]]) –
order of the norm. The following mathematical norms must be supported:
ord
description
1
L1-norm (Manhattan)
2
L2-norm (Euclidean)
inf
infinity norm
(int,float >= 1)
p-norm
The following non-mathematical “norms” must be supported:
ord
description
0
sum(a != 0)
-1
1./sum(1./abs(a))
-2
1./sqrt(sum(1./abs(a)**2))
-inf
min(abs(a))
(int,float < 1)
sum(abs(a)**ord)**(1./ord)
Default:
2.
- Returns:
out – an array containing the vector norms. If
axisisNone, the returned array must be a zero-dimensional array containing a vector norm. Ifaxisis a scalar value (intorfloat), the returned array must have a rank which is one less than the rank ofx. Ifaxisis an-tuple, the returned array must have a rank which isnless than the rank ofx. Ifxhas a real-valued data type, the returned array must have a real-valued floating-point data type determined by type-promotion. Ifxhas a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- class array_api._2025_12.NestedSequence(*args, **kwargs)[source]¶
Bases:
Protocol,Generic- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- type array_api._2025_12.ShapedAnyArray = ShapedArray[Unpack[T], Any, Any]¶
- class array_api._2025_12.ShapedArray[source]¶
Bases:
Array,Protocol,Generic[Unpack[T],TDevice,TDtype]- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- property shape: tuple[*T]¶
Array dimensions.
- Returns:
out – array dimensions. An array dimension must be
Noneif and only if a dimension is unknown.- Return type:
Tuple[Optional[int], …]
Note
For array libraries having graph-based computational models, array dimensions may be unknown due to data-dependent operations (e.g., boolean indexing;
A[:, B > 0]) and thus cannot be statically resolved without knowing array contents.Note
The returned value should be a tuple; however, where warranted, an array library may choose to return a custom shape object. If an array library returns a custom shape object, the object must be immutable, must support indexing for dimension retrieval, and must behave similarly to a tuple.
- class array_api._2025_12.abs(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the absolute value for each element
x_iof the input arrayx.For real-valued input arrays, the element-wise result has the same magnitude as the respective element in
xbut has positive sign.Note
For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent.
Note
For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number \(z = a + bj\) is computed as
\[\operatorname{abs}(z) = \sqrt{a^2 + b^2}\]Note
For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation.
- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the absolute value of each element in
x. Ifxhas a real-valued data type, the returned array must have the same data type asx. Ifxhas a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type).- Return type:
array
Notes
Special Cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis-0, the result is+0.If
x_iis-infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+infinityor-infinityandbis any value (includingNaN), the result is+infinity.If
ais any value (includingNaN) andbis either+infinityor-infinity, the result is+infinity.If
ais either+0or-0, the result is equal toabs(b).If
bis either+0or-0, the result is equal toabs(a).If
aisNaNandbis a finite number, the result isNaN.If
ais a finite number andbisNaN, the result isNaN.If
aisNaNandbisNaN, the result isNaN.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.acos(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation of the principal value of the inverse cosine for each element
x_iof the input arrayx.Each element-wise result is expressed in radians.
Note
The principal value of the arc cosine of a complex number \(z\) is
\[\operatorname{acos}(z) = \frac{1}{2}\pi + j\ \ln(zj + \sqrt{1-z^2})\]For any \(z\),
\[\operatorname{acos}(z) = \pi - \operatorname{acos}(-z)\]Note
For complex floating-point operands,
acos(conj(x))must equalconj(acos(x)).Note
The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty, -1)\) and \((1, \infty)\) of the real axis.
Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval \([0, \pi]\) along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the inverse cosine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis greater than1, the result isNaN.If
x_iis less than-1, the result isNaN.If
x_iis1, the result is+0.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result isπ/2 - 0j.If
ais either+0or-0andbisNaN, the result isπ/2 + NaN j.If
ais a finite number andbis+infinity, the result isπ/2 - infinity j.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais-infinityandbis a positive (i.e., greater than0) finite number, the result isπ - infinity j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+0 - infinity j.If
ais-infinityandbis+infinity, the result is3π/4 - infinity j.If
ais+infinityandbis+infinity, the result isπ/4 - infinity j.If
ais either+infinityor-infinityandbisNaN, the result isNaN ± infinity j(sign of the imaginary component is unspecified).If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result isNaN - infinity j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.acosh(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the inverse hyperbolic cosine for each element
x_iof the input arrayx.Note
The principal value of the inverse hyperbolic cosine of a complex number \(z\) is
\[\operatorname{acosh}(z) = \ln(z + \sqrt{z+1}\sqrt{z-1})\]For any \(z\),
\[\operatorname{acosh}(z) = \frac{\sqrt{z-1}}{\sqrt{1-z}}\operatorname{acos}(z)\]or simply
\[\operatorname{acosh}(z) = j\ \operatorname{acos}(z)\]in the upper half of the complex plane.
Note
For complex floating-point operands,
acosh(conj(x))must equalconj(acosh(x)).Note
The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment \((-\infty, 1)\) of the real axis.
Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval \([0, \infty)\) along the real axis and in the interval \([-\pi j, +\pi j]\) along the imaginary axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type.
- Returns:
out – an array containing the inverse hyperbolic cosine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than1, the result isNaN.If
x_iis1, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result is+0 + πj/2.If
ais a finite number andbis+infinity, the result is+infinity + πj/2.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais+0andbisNaN, the result isNaN ± πj/2(sign of imaginary component is unspecified).If
ais-infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + πj.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0j.If
ais-infinityandbis+infinity, the result is+infinity + 3πj/4.If
ais+infinityandbis+infinity, the result is+infinity + πj/4.If
ais either+infinityor-infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is+infinity + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.add(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the sum for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float, complex]) – first input array. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – second input array. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise sums. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For real-valued floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis+infinityandx2_iis-infinity, the result isNaN.If
x1_iis-infinityandx2_iis+infinity, the result isNaN.If
x1_iis+infinityandx2_iis+infinity, the result is+infinity.If
x1_iis-infinityandx2_iis-infinity, the result is-infinity.If
x1_iis+infinityandx2_iis a finite number, the result is+infinity.If
x1_iis-infinityandx2_iis a finite number, the result is-infinity.If
x1_iis a finite number andx2_iis+infinity, the result is+infinity.If
x1_iis a finite number andx2_iis-infinity, the result is-infinity.If
x1_iis-0andx2_iis-0, the result is-0.If
x1_iis-0andx2_iis+0, the result is+0.If
x1_iis+0andx2_iis-0, the result is+0.If
x1_iis+0andx2_iis+0, the result is+0.If
x1_iis either+0or-0andx2_iis a nonzero finite number, the result isx2_i.If
x1_iis a nonzero finite number andx2_iis either+0or-0, the result isx1_i.If
x1_iis a nonzero finite number andx2_iis-x1_i, the result is+0.In the remaining cases, when neither
infinity,+0,-0, nor aNaNis involved, and the operands have the same mathematical sign or have different magnitudes, the sum must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported round mode. If the magnitude is too large to represent, the operation overflows and the result is an infinity of appropriate mathematical sign.
Note
Floating-point addition is a commutative operation, but not always associative.
For complex floating-point operands, addition is defined according to the following table. For real components
aandcand imaginary componentsbandd,c
dj
c + dj
a
a + c
a + dj
(a+c) + dj
bj
c + bj
(b+d)j
c + (b+d)j
a + bj
(a+c) + bj
a + (b+d)j
(a+c) + (b+d)j
For complex floating-point operands, real-valued floating-point special cases must independently apply to the real and imaginary component operations involving real numbers as described in the above table. For example, let
a = real(x1_i),b = imag(x1_i),c = real(x2_i),d = imag(x2_i), andIf
ais-0andcis-0, the real component of the result is-0.Similarly, if
bis+0anddis-0, the imaginary component of the result is+0.
Hence, if
z1 = a + bj = -0 + 0jandz2 = c + dj = -0 - 0j, the result ofz1 + z2is-0 + 0j.Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.all(*args, **kwargs)[source]¶
Bases:
Protocol,GenericTests whether all input array elements evaluate to
Truealong a specified axis.- Parameters:
x (array) – input array.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid
axismust be an integer on the interval[-N, N), whereNis the number of axes inx. If anaxisis specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last axis (where-1refers to the last axis). If provided an invalidaxis, the function must raise an exception. Default:None.keepdims (bool) – If
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result. Otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of
bool.- Return type:
array
Notes
Positive infinity, negative infinity, and NaN must evaluate to
True.If
xhas a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate toTrue.If
xis an empty array or the size of the axis along which to evaluate elements is zero, the test result must beTrue.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.any(*args, **kwargs)[source]¶
Bases:
Protocol,GenericTests whether any input array element evaluates to
Truealong a specified axis.- Parameters:
x (array) – input array.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid
axismust be an integer on the interval[-N, N), whereNis the number of axes inx. If anaxisis specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where-1refers to the last axis). If provided an invalidaxis, the function must raise an exception. Default:None.keepdims (bool) – If
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result. Otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of
bool.- Return type:
array
Notes
Positive infinity, negative infinity, and NaN must evaluate to
True.If
xhas a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate toTrue.If
xis an empty array or the size of the axis along which to evaluate elements is zero, the test result must beFalse.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.arange(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns evenly spaced values within the half-open interval
[start, stop)as a one-dimensional array.- Parameters:
start (Union[int, float]) – if
stopis specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). Ifstopis not specified, the default starting value is0.stop (Optional[Union[int, float]]) – the end of the interval. Default:
None.step (Union[int, float]) – the distance between two adjacent elements (
out[i+1] - out[i]). Must not be0; may be negative, this results in an empty array ifstop >= start. Default:1.dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be inferred fromstart,stopandstep. If those are all integers, the output array dtype must be the default integer dtype; if one or more have typefloat, then the output array dtype must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
Note
This function cannot guarantee that the interval does not include the
stopvalue in those cases wherestepis not an integer and floating-point rounding errors affect the length of the output array.- Returns:
out – a one-dimensional array containing evenly spaced values. The length of the output array must be
ceil((stop-start)/step)ifstop - startandstephave the same sign, and length0otherwise.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.argmax(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the indices of the maximum values along a specified axis.
When the maximum value occurs multiple times, only the indices corresponding to the first occurrence are returned.
- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (Optional[int]) – axis along which to search. If
None, the function must return the index of the maximum value of the flattened array. If notNone, a valid axis must be an integer on the interval[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if
axisisNone, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array must have be the default array index data type.- Return type:
array
Notes
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.argmin(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the indices of the minimum values along a specified axis.
When the minimum value occurs multiple times, only the indices corresponding to the first occurrence are returned.
- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (Optional[int]) – axis along which to search. If
None, the function must return the index of the minimum value of the flattened array. If notNone, a valid axis must be an integer on the interval[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if
axisisNone, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array must have the default array index data type.- Return type:
array
Notes
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.argsort(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the indices that sort an array
xalong a specified axis.- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (int) – axis along which to sort. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:-1.descending (bool) – sort order. If
True, the returned indices must sortxin descending order (by value). IfFalse, the returned indices must sortxin ascending order (by value). Default:False.stable (bool) – sort stability. If
True, the returned indices must maintain the relative order ofxvalues which compare as equal. IfFalse, the returned indices may maintain the relative order ofxvalues which compare as equal (i.e., the relative order ofxvalues which compare as equal is implementation-dependent). Default:True.
- Returns:
out – an array of indices. The returned array must have the same shape as
x. The returned array must have the default array index data type.- Return type:
array
Notes
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.asarray(*args, **kwargs)[source]¶
Bases:
Protocol,GenericConvert the input to an array.
- Parameters:
obj (Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol]) –
object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol.
Tip
An object supporting the buffer protocol can be turned into a memoryview through
memoryview(obj).dtype (Optional[dtype]) –
output array data type. If
dtypeisNone, the output array data type must be inferred from the data type(s) inobj. If all input values are Python scalars, then, in order of precedence,if all values are of type
bool, the output data type must bebool.if all values are of type
intor are a mixture ofboolandint, the output data type must be the default integer data type.if one or more values are
complexnumbers, the output data type must be the default complex floating-point data type.if one or more values are
floats, the output data type must be the default real-valued floating-point data type.
Default:
None.device (Optional[device]) – device on which to place the created array. If
deviceisNoneandobjis an array, the output array device must be inferred fromobj. Default:None.copy (Optional[bool]) – boolean indicating whether or not to copy the input. If
True, the function must always copy (see copy-keyword-argument). IfFalse, the function must never copy for input which supports the buffer protocol and must raise aValueErrorin case a copy would be necessary. IfNone, the function must reuse existing memory buffer if possible and copy otherwise. Default:None.
- Returns:
out – an array containing the data from
obj.- Return type:
array
Notes
If
objis a sequence with some elements being arrays, behavior is unspecified and thus implementation-defined. Conforming implementations may perform a conversion or raise an exception. To join a sequence of arrays along a new axis, seestack().If
dtypeis notNone, then array conversions should obey type-promotion rules. Conversions not specified according to type-promotion rules may or may not be permitted by a conforming array library. To perform an explicit cast, usearray_api.astype().If an input value exceeds the precision of the resolved output array data type, behavior is unspecified and thus implementation-defined.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.asin(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation of the principal value of the inverse sine for each element
x_iof the input arrayx.Each element-wise result is expressed in radians.
Note
The principal value of the arc sine of a complex number \(z\) is
\[\operatorname{asin}(z) = -j\ \ln(zj + \sqrt{1-z^2})\]For any \(z\),
\[\operatorname{asin}(z) = \operatorname{acos}(-z) - \frac{\pi}{2}\]Note
For complex floating-point operands,
asin(conj(x))must equalconj(asin(x)).Note
The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty, -1)\) and \((1, \infty)\) of the real axis.
Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval \([-\pi/2, +\pi/2]\) along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the inverse sine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis greater than1, the result isNaN.If
x_iis less than-1, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
-1j * asinh(x*1j).Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.asinh(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the inverse hyperbolic sine for each element
x_iin the input arrayx.Note
The principal value of the inverse hyperbolic sine of a complex number \(z\) is
\[\operatorname{asinh}(z) = \ln(z + \sqrt{1+z^2})\]For any \(z\),
\[\operatorname{asinh}(z) = \frac{\operatorname{asin}(zj)}{j}\]Note
For complex floating-point operands,
asinh(conj(x))must equalconj(asinh(x))andasinh(-z)must equal-asinh(z).Note
The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty j, -j)\) and \((j, \infty j)\) of the imaginary axis.
Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval \([-\pi j/2, +\pi j/2]\) along the imaginary axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type.
- Returns:
out – an array containing the inverse hyperbolic sine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais+0andbis+0, the result is+0 + 0j.If
ais a positive (i.e., greater than0) finite number andbis+infinity, the result is+infinity + πj/2.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0j.If
ais+infinityandbis+infinity, the result is+infinity + πj/4.If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis a nonzero finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is±infinity + NaN j(sign of the real component is unspecified).If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.astype(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCopies an array to a specified data type irrespective of type-promotion rules.
Note
Casting floating-point
NaNandinfinityvalues to integral data types is not specified and is implementation-dependent.Note
Casting a complex floating-point array to a real-valued data type should not be permitted.
Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array
x,astype(x)equalsastype(real(x))). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point arrayx,astype(x)andastype(real(x))versus onlyastype(imag(x))). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type.Note
When casting a boolean input array to a real-valued data type, a value of
Truemust cast to a real-valued number equal to1, and a value ofFalsemust cast to a real-valued number equal to0.When casting a boolean input array to a complex floating-point data type, a value of
Truemust cast to a complex number equal to1 + 0j, and a value ofFalsemust cast to a complex number equal to0 + 0j.Note
When casting a real-valued input array to
bool, a value of0must cast toFalse, and a non-zero value must cast toTrue.When casting a complex floating-point array to
bool, a value of0 + 0jmust cast toFalse, and all other values must cast toTrue.- Parameters:
x (array) – array to cast.
dtype (dtype) – desired data type.
copy (bool) – specifies whether to copy an array when the specified
dtypematches the data type of the input arrayx. IfTrue, a newly allocated array must always be returned (see copy-keyword-argument). IfFalseand the specifieddtypematches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default:True.device (Optional[device]) – device on which to place the returned array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the specified data type. The returned array must have the same shape as
x.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Added device keyword argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.atan(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation of the principal value of the inverse tangent for each element
x_iof the input arrayx.Each element-wise result is expressed in radians.
Note
The principal value of the inverse tangent of a complex number \(z\) is
\[\operatorname{atan}(z) = -\frac{\ln(1 - zj) - \ln(1 + zj)}{2}j\]Note
For complex floating-point operands,
atan(conj(x))must equalconj(atan(x)).Note
The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty j, -j)\) and \((+j, \infty j)\) of the imaginary axis.
Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval \([-\pi/2, +\pi/2]\) along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the inverse tangent of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is an implementation-dependent approximation to+π/2.If
x_iis-infinity, the result is an implementation-dependent approximation to-π/2.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
-1j * atanh(x*1j).Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.atan2(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation of the inverse tangent of the quotient
x1/x2, having domain[-infinity, +infinity] x [-infinity, +infinity](where thexnotation denotes the set of ordered pairs of elements(x1_i, x2_i)) and codomain[-π, +π], for each pair of elements(x1_i, x2_i)of the input arraysx1andx2, respectively. Each element-wise result is expressed in radians.The mathematical signs of
x1_iandx2_idetermine the quadrant of each element-wise result. The quadrant (i.e., branch) is chosen such that each element-wise result is the signed angle in radians between the ray ending at the origin and passing through the point(1,0)and the ray ending at the origin and passing through the point(x2_i, x1_i).Note
Note the role reversal: the “y-coordinate” is the first function parameter; the “x-coordinate” is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second.
By IEEE 754 convention, the inverse tangent of the quotient
x1/x2is defined forx2_iequal to positive or negative zero and for either or both ofx1_iandx2_iequal to positive or negativeinfinity.- Parameters:
x1 (Union[array, int, float]) – input array corresponding to the y-coordinates. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – input array corresponding to the x-coordinates. Must be compatible with
x1(see broadcasting). Should have a real-valued floating-point data type.
- Returns:
out – an array containing the inverse tangent of the quotient
x1/x2. The returned array must have a real-valued floating-point data type determined by type-promotion.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis greater than0andx2_iis+0, the result is an implementation-dependent approximation to+π/2.If
x1_iis greater than0andx2_iis-0, the result is an implementation-dependent approximation to+π/2.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis+0andx2_iis+0, the result is+0.If
x1_iis+0andx2_iis-0, the result is an implementation-dependent approximation to+π.If
x1_iis+0andx2_iis less than0, the result is an implementation-dependent approximation to+π.If
x1_iis-0andx2_iis greater than0, the result is-0.If
x1_iis-0andx2_iis+0, the result is-0.If
x1_iis-0andx2_iis-0, the result is an implementation-dependent approximation to-π.If
x1_iis-0andx2_iis less than0, the result is an implementation-dependent approximation to-π.If
x1_iis less than0andx2_iis+0, the result is an implementation-dependent approximation to-π/2.If
x1_iis less than0andx2_iis-0, the result is an implementation-dependent approximation to-π/2.If
x1_iis greater than0,x1_iis a finite number, andx2_iis+infinity, the result is+0.If
x1_iis greater than0,x1_iis a finite number, andx2_iis-infinity, the result is an implementation-dependent approximation to+π.If
x1_iis less than0,x1_iis a finite number, andx2_iis+infinity, the result is-0.If
x1_iis less than0,x1_iis a finite number, andx2_iis-infinity, the result is an implementation-dependent approximation to-π.If
x1_iis+infinityandx2_iis a finite number, the result is an implementation-dependent approximation to+π/2.If
x1_iis-infinityandx2_iis a finite number, the result is an implementation-dependent approximation to-π/2.If
x1_iis+infinityandx2_iis+infinity, the result is an implementation-dependent approximation to+π/4.If
x1_iis+infinityandx2_iis-infinity, the result is an implementation-dependent approximation to+3π/4.If
x1_iis-infinityandx2_iis+infinity, the result is an implementation-dependent approximation to-π/4.If
x1_iis-infinityandx2_iis-infinity, the result is an implementation-dependent approximation to-3π/4.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.atanh(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the inverse hyperbolic tangent for each element
x_iof the input arrayx.Note
The principal value of the inverse hyperbolic tangent of a complex number \(z\) is
\[\operatorname{atanh}(z) = \frac{\ln(1+z)-\ln(z-1)}{2}\]For any \(z\),
\[\operatorname{atanh}(z) = \frac{\operatorname{atan}(zj)}{j}\]Note
For complex floating-point operands,
atanh(conj(x))must equalconj(atanh(x))andatanh(-x)must equal-atanh(x).Note
The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments \((-\infty, 1]\) and \([1, \infty)\) of the real axis.
Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval \([-\pi j/2, +\pi j/2]\) along the imaginary axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type.
- Returns:
out – an array containing the inverse hyperbolic tangent of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than-1, the result isNaN.If
x_iis greater than1, the result isNaN.If
x_iis-1, the result is-infinity.If
x_iis+1, the result is+infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais+0andbis+0, the result is+0 + 0j.If
ais+0andbisNaN, the result is+0 + NaN j.If
ais1andbis+0, the result is+infinity + 0j.If
ais a positive (i.e., greater than0) finite number andbis+infinity, the result is+0 + πj/2.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+0 + πj/2.If
ais+infinityandbis+infinity, the result is+0 + πj/2.If
ais+infinityandbisNaN, the result is+0 + NaN j.If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is±0 + πj/2(sign of the real component is unspecified).If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.bitwise_and(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the bitwise AND of the underlying binary representation of each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.bitwise_invert(*args, **kwargs)[source]¶
Bases:
Protocol,GenericInverts (flips) each bit for each element
x_iof the input arrayx.- Parameters:
x (array) – input array. Should have an integer or boolean data type.
- Returns:
out – an array containing the element-wise results. The returned array must have the same data type as
x.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.bitwise_left_shift(*args, **kwargs)[source]¶
Bases:
Protocol,GenericShifts the bits of each element
x1_iof the input arrayx1to the left by appendingx2_i(i.e., the respective element in the input arrayx2) zeros to the right ofx1_i.- Parameters:
x1 (Union[array, int]) – first input array. Should have an integer data type.
x2 (Union[array, int]) – second input array. Must be compatible with
x1(see broadcasting). Should have an integer data type. Each element must be greater than or equal to0.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.bitwise_or(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the bitwise OR of the underlying binary representation of each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.bitwise_right_shift(*args, **kwargs)[source]¶
Bases:
Protocol,GenericShifts the bits of each element
x1_iof the input arrayx1to the right according to the respective elementx2_iof the input arrayx2.Note
This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two.
- Parameters:
x1 (Union[array, int]) – first input array. Should have an integer data type.
x2 (Union[array, int]) – second input array. Must be compatible with
x1(see broadcasting). Should have an integer data type. Each element must be greater than or equal to0.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.bitwise_xor(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the bitwise XOR of the underlying binary representation of each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.broadcast_arrays(*args, **kwargs)[source]¶
Bases:
Protocol,GenericBroadcasts one or more arrays against one another.
- Parameters:
arrays (array) – an arbitrary number of to-be broadcasted arrays.
- Returns:
out – tuple of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array.
- Return type:
Tuple[array, …]
Notes
Changed in version 2025.12: Changed the return value from a List to a Tuple.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.broadcast_shapes(*args, **kwargs)[source]¶
Bases:
ProtocolBroadcasts one or more shapes against one another.
- Parameters:
shapes (Tuple[Optional[int], ...]) – an arbitrary number of to-be broadcasted shapes.
- Returns:
out – a single broadcasted shape obtained by applying broadcasting rules (see broadcasting) to each of the input shapes against one another.
- Return type:
Tuple[Optional[int], …]
- Raises:
ValueError – If provided shapes which are not broadcast compatible (see broadcasting), a
ValueErrorshould be raised.
Notes
If not provided one or more arguments, the function must return an empty tuple.
Array-conforming libraries which build computation graphs (e.g., ndonnx and Dask) and which need to provide a mechanism for indicating dimensions of unknown size may accept non-integer values (e.g.,
None). For these libraries, dimensions of unknown size must be propagated to the returned shape.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.broadcast_to(*args, **kwargs)[source]¶
Bases:
Protocol,GenericBroadcasts an array to a specified shape.
- Parameters:
x (array) – array to broadcast. Must be capable of being broadcast to the specified
shape(see broadcasting). If the array is incompatible with the specified shape, the function must raise an exception.shape (Tuple[int, ...]) – array shape.
- Returns:
out (array) – an array having the specified shape. Must have the same data type as
x... versionchanged:: 2024.12 – Clarified broadcast behavior.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.can_cast(*args, **kwargs)[source]¶
Bases:
Protocol,GenericDetermines if one data type can be cast to another data type according to type promotion rules (see type-promotion).
- Parameters:
- Returns:
out –
Trueif the cast can occur according to type promotion rules (see type-promotion); otherwise,False.- Return type:
Notes
When
from_is a data type, the function must determine whether the data type can be cast to another data type according to the complete type promotion rules (see type-promotion) described in this specification, irrespective of whether a conforming array library supports devices which do not have full data type support.When
from_is an array, the function must determine whether the data type of the array can be cast to the desired data type according to the type promotion graph of the array device. As not all devices can support all data types, full support for type promotion rules (see type-promotion) may not be possible. Accordingly, the output ofcan_cast(array, dtype)may differ fromcan_cast(array.dtype, dtype).
Changed in version 2024.12: Required that the application of type promotion rules must account for device context.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.ceil(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRounds each element
x_iof the input arrayxto the smallest (i.e., closest to-infinity) integer-valued number that is not less thanx_i.- Parameters:
x (array) – input array. Should have a real-valued data type.
- Returns:
out – an array containing the rounded result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
If
x_iis already integer-valued, the result isx_i.
For floating-point operands,
If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iisNaN, the result isNaN.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.cholesky(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the lower (upper) Cholesky decomposition of a complex Hermitian or real symmetric positive-definite matrix
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The lower Cholesky decomposition of a complex Hermitian or real symmetric positive-definite matrix \(x \in\ \mathbb{K}^{n \times n}\) is defined as
\[x = LL^{H} \qquad \text{L $\in\ \mathbb{K}^{n \times n}$}\]where \(L\) is a lower triangular matrix and \(L^{H}\) is the conjugate transpose when \(L\) is complex-valued and the transpose when \(L\) is real-valued.
The upper Cholesky decomposition is defined similarly
\[x = U^{H}U \qquad \text{U $\in\ \mathbb{K}^{n \times n}$}\]where \(U\) is an upper triangular matrix.
When
xis a stack of matrices, the function must compute the Cholesky decomposition for each matrix in the stack.Note
Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined.
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type.upper (bool) – If
True, the result must be the upper-triangular Cholesky factor \(U\). IfFalse, the result must be the lower-triangular Cholesky factor \(L\). Default:False.
- Returns:
out – an array containing the Cholesky factors for each square matrix. If
upperisFalse, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by type-promotion and must have the same shape asx.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.clip(*args, **kwargs)[source]¶
Bases:
Protocol,GenericClamps each element
x_iof the input arrayxto the range[min, max].- Parameters:
x (array) – input array. Should have a real-valued data type.
min (Optional[Union[int, float, array]]) – lower-bound of the range to which to clamp. If
None, no lower bound must be applied. Must be compatible withxandmax(see broadcasting). Should have the same data type asx. Default:None.max (Optional[Union[int, float, array]]) – upper-bound of the range to which to clamp. If
None, no upper bound must be applied. Must be compatible withxandmin(see broadcasting). Should have the same data type asx. Default:None.
- Returns:
out – an array containing element-wise results. The returned array should have the same data type as
x.- Return type:
array
Notes
This function is conceptually equivalent to
maximum(minimum(x, max), min)whenx,min, andmaxhave the same data type.If both
minandmaxareNone, the elements of the returned array must equal the respective elements inx.If a broadcasted element in
minis greater than a corresponding broadcasted element inmax, behavior is unspecified and thus implementation-dependent.For scalar
minand/ormax, the scalar values should follow type promotion rules for operations involving arrays and scalar operands (see type-promotion).If
xhas an integral data type and a broadcasted element inminormaxis outside the bounds of the data type ofx, behavior is unspecified and thus implementation-dependent.If either
minormaxis an array having a different data type thanx, behavior is unspecified and thus implementation-dependent.
Special cases
If
x_iisNaN, the result isNaN.If
min_iisNaN, the result isNaN.If
max_iisNaN, the result isNaN.
Added in version 2023.12.
Changed in version 2024.12: Added special case behavior when one of the operands is
NaN.Changed in version 2024.12: Clarified that behavior is only defined when
x,min, andmaxresolve to arrays having the same data type.Changed in version 2024.12: Clarified that behavior is only defined when elements of
minandmaxare inside the bounds of the input array data type.- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.concat(*args, **kwargs)[source]¶
Bases:
Protocol,GenericJoins a sequence of arrays along an existing axis.
- Parameters:
arrays (Union[Tuple[array, ...], List[array]]) – input arrays to join. The arrays must have the same shape, except in the dimension specified by
axis.axis (Optional[int]) – axis along which to join the arrays. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes in each array. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. IfaxisisNone, arrays must be flattened before concatenation. Default:0.
- Returns:
out – an output array containing the concatenated values. If the input arrays have different data types, normal type-promotion must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays.
Note
This specification leaves type promotion between data type families (i.e.,
intxxandfloatxx) unspecified and thus implementation-defined.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.conj(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the complex conjugate for each element
x_iof the input arrayx.For complex numbers of the form
\[a + bj\]the complex conjugate is defined as
\[a - bj\]Hence, the returned complex conjugates must be computed by negating the imaginary component of each element
x_i.- Parameters:
x (array) – input array. Must have a numeric data type.
- Returns:
out – an array containing the element-wise results. The returned array must have the same data type as
x.- Return type:
array
Notes
Whether the returned array and the input array share the same underlying memory is unspecified and thus implementation-defined.
Added in version 2022.12.
Changed in version 2024.12: Added support for real-valued arrays.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.copysign(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComposes a floating-point value with the magnitude of
x1_iand the sign ofx2_ifor each element of the input arrayx1.- Parameters:
x1 (Union[array, int, float]) – input array containing magnitudes. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – input array whose sign bits are applied to the magnitudes of
x1. Must be compatible withx1(see broadcasting). Should have a real-valued floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For real-valued floating-point operands, let
|x|be the absolute value, and ifx1_iis notNaN,If
x2_iis less than0, the result is-|x1_i|.If
x2_iis-0, the result is-|x1_i|.If
x2_iis+0, the result is|x1_i|.If
x2_iis greater than0, the result is|x1_i|.If
x2_iisNaNand the sign bit ofx2_iis1, the result is-|x1_i|.If
x2_iisNaNand the sign bit ofx2_iis0, the result is|x1_i|.If
x1_iisNaNandx2_iis less than0, the result isNaNwith a sign bit of1.If
x1_iisNaNandx2_iis-0, the result isNaNwith a sign bit of1.If
x1_iisNaNandx2_iis+0, the result isNaNwith a sign bit of0.If
x1_iisNaNandx2_iis greater than0, the result isNaNwith a sign bit of0.If
x1_iisNaNandx2_iisNaNand the sign bit ofx2_iis1, the result isNaNwith a sign bit of1.If
x1_iisNaNandx2_iisNaNand the sign bit ofx2_iis0, the result isNaNwith a sign bit of0.
Added in version 2023.12.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.cos(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the cosine for each element
x_iof the input arrayx.Each element
x_iis assumed to be expressed in radians.Note
The cosine is an entire function on the complex plane and has no branch cuts.
Note
For complex arguments, the mathematical definition of cosine is
\[\begin{split}\begin{align} \operatorname{cos}(x) &= \sum_{n=0}^\infty \frac{(-1)^n}{(2n)!} x^{2n} \\ &= \frac{e^{jx} + e^{-jx}}{2} \\ &= \operatorname{cosh}(jx) \end{align}\end{split}\]where \(\operatorname{cosh}\) is the hyperbolic cosine.
- Parameters:
x (array) – input array whose elements are each expressed in radians. Should have a floating-point data type.
- Returns:
out – an array containing the cosine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is1.If
x_iis-0, the result is1.If
x_iis+infinity, the result isNaN.If
x_iis-infinity, the result isNaN.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
cosh(x*1j).Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.cosh(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the hyperbolic cosine for each element
x_iin the input arrayx.The mathematical definition of the hyperbolic cosine is
\[\operatorname{cosh}(x) = \frac{e^x + e^{-x}}{2}\]Note
The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period \(2\pi j\), with respect to the imaginary component.
- Parameters:
x (array) – input array whose elements each represent a hyperbolic angle. Should have a floating-point data type.
- Returns:
out – an array containing the hyperbolic cosine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
Note
For all operands,
cosh(x)must equalcosh(-x).For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is1.If
x_iis-0, the result is1.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andNote
For complex floating-point operands,
cosh(conj(x))must equalconj(cosh(x)).If
ais+0andbis+0, the result is1 + 0j.If
ais+0andbis+infinity, the result isNaN + 0j(sign of the imaginary component is unspecified).If
ais+0andbisNaN, the result isNaN + 0j(sign of the imaginary component is unspecified).If
ais a nonzero finite number andbis+infinity, the result isNaN + NaN j.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis+0, the result is+infinity + 0j.If
ais+infinityandbis a nonzero finite number, the result is+infinity * cis(b).If
ais+infinityandbis+infinity, the result is+infinity + NaN j(sign of the real component is unspecified).If
ais+infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis either+0or-0, the result isNaN + 0j(sign of the imaginary component is unspecified).If
aisNaNandbis a nonzero finite number, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
where
cis(v)iscos(v) + sin(v)*1j.Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.count_nonzero(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCounts the number of array elements which are non-zero.
- Parameters:
x (array) – input array.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to count non-zero values. By default, the number of non-zero values must be computed over the entire array. If a tuple of integers, the number of non-zero values must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes must not be included in the result. Default:False.
- Returns:
out – if the number of non-zeros values was computed over the entire array, a zero-dimensional array containing the total number of non-zero values; otherwise, a non-zero-dimensional array containing the counts along the specified axes. The returned array must have the default array index data type.
- Return type:
array
Notes
If
xhas a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero.If
xhas a boolean data type, non-zero elements are those elements which are equal toTrue.
Added in version 2024.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.cross(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the cross product of 3-element vectors.
If
x1and/orx2are multi-dimensional arrays (i.e., the broadcasted result has a rank greater than1), then the cross-product of each pair of corresponding 3-element vectors is independently computed.- Parameters:
x1 (array) – first input array. Must have a numeric data type. The size of the axis over which the cross product is to be computed must be equal to 3.
x2 (array) –
second input array. Must be broadcast compatible with
x1along all axes other than the axis along which the cross-product is computed (see broadcasting). The size of the axis over which the cross product is to be computed must be equal to 3. Must have a numeric data type.Note
The compute axis (dimension) must not be broadcasted.
axis (int) – the axis (dimension) of
x1andx2containing the vectors for which to compute the cross product. Should be an integer on the interval[-N, -1], whereNismin(x1.ndim, x2.ndim). The function must determine the axis along which to compute the cross product by counting backward from the last dimension (where-1refers to the last dimension). By default, the function must compute the cross product over the last axis. Default:-1.
- Returns:
out – an array containing the cross products. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
Raises
if the size of the axis over which to compute the cross product is not equal to
3(before broadcasting) for bothx1andx2.
Changed in version 2022.12: Added support for broadcasting.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Restricted broadcasting to only non-compute axes and required that
axisbe a negative integer.- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.cumulative_prod(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the cumulative product of elements in the input array
x.- Parameters:
x (array) – input array. Should have one or more dimensions (axes). Should have a numeric data type.
axis (Optional[int]) –
axis along which to compute the cumulative product. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.If
xis a one-dimensional array, providing anaxismust be optional; however, ifxhas more than one dimension, providing anaxismust be required.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the product (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.include_initial (bool) – boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the multiplicative identity (i.e., one). Default:
False.
- Returns:
out – an array containing the cumulative products. The returned array must have a data type as described by the
dtypeparameter above.Let
Mbe the size of the axis along which to compute the cumulative product. The returned array must have a shape determined according to the following rules:if
include_initialisTrue, the returned array must have the same shape asx, except the size of the axis along which to compute the cumulative product must beM+1.if
include_initialisFalse, the returned array must have the same shape asx.
- Return type:
array
Notes
When
xis a zero-dimensional array, behavior is unspecified and thus implementation-defined.
Special Cases
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
multiply().Added in version 2024.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.cumulative_sum(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the cumulative sum of elements in the input array
x.- Parameters:
x (array) – input array. Should have one or more dimensions (axes). Should have a numeric data type.
axis (Optional[int]) –
axis along which to compute the cumulative sum. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.If
xis a one-dimensional array, providing anaxismust be optional; however, ifxhas more than one dimension, providing anaxismust be required.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the sum (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.include_initial (bool) – boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the additive identity (i.e., zero). Default:
False.
- Returns:
out – an array containing the cumulative sums. The returned array must have a data type as described by the
dtypeparameter above.Let
Mbe the size of the axis along which to compute the cumulative sum. The returned array must have a shape determined according to the following rules:if
include_initialisTrue, the returned array must have the same shape asx, except the size of the axis along which to compute the cumulative sum must beM+1.if
include_initialisFalse, the returned array must have the same shape asx.
- Return type:
array
Notes
When
xis a zero-dimensional array, behavior is unspecified and thus implementation-defined.
Special Cases
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
add().Added in version 2023.12.
Changed in version 2024.12: Behavior when providing a zero-dimensional array is explicitly left unspecified.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.det(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the determinant of a square matrix (or a stack of square matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – if
xis a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type asx.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.diagonal(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the specified diagonals of a matrix (or a stack of matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices.offset (int) –
offset specifying the off-diagonal relative to the main diagonal.
offset = 0: the main diagonal.offset > 0: off-diagonal above the main diagonal.offset < 0: off-diagonal below the main diagonal.
Default: 0.
- Returns:
out – an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as
x.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.diff(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the n-th discrete forward difference along a specified axis.
- Parameters:
x (array) – input array. Should have a numeric data type.
axis (int) – axis along which to compute differences. A valid
axismust be an integer on the interval[-N, N), whereNis the number of axes inx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute differences by counting backward from the last axis (where-1refers to the last axis). If provided an invalidaxis, the function must raise an exception. Default:-1.n (int) – number of times to recursively compute differences. Default:
1.prepend (Optional[array]) – values to prepend to a specified axis prior to computing differences. Must have the same shape as
x, except for the axis specified byaxiswhich can have any size. Should have the same data type asx. Default:None.append (Optional[array]) – values to append to a specified axis prior to computing differences. Must have the same shape as
x, except for the axis specified byaxiswhich can have any size. Should have the same data type asx. Default:None.
- Returns:
out – an array containing the n-th differences. Should have the same data type as
x. Must have the same shape asx, except for the axis specified byaxiswhich must have a size determined as follows:Let
Mbe the number of elements along an axis specified byaxis.Let
N1be the number of prepended values along an axis specified byaxis.Let
N2be the number of appended values along an axis specified byaxis.The final size of the axis specified by
axismust beM + N1 + N2 - n.
- Return type:
array
Notes
The first-order differences are given by
out[i] = x[i+1] - x[i]along a specified axis. Higher-order differences must be calculated recursively (e.g., by callingdiff(out, axis=axis, n=n-1)).If a conforming implementation chooses to support
prependandappendarrays which have a different data type thanx, behavior is unspecified and thus implementation-defined. Implementations may choose to type promote (type-promotion), castprependand/orappendto the same data type asx, or raise an exception.
Added in version 2024.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.divide(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the division of each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float, complex]) – dividend input array. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – divisor input array. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.If one or both of the input arrays have integer data types, the result is implementation-dependent, as type promotion between data type “kinds” (e.g., integer versus floating-point) is unspecified.
Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type.
Special cases
For real-valued floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis either+infinityor-infinityandx2_iis either+infinityor-infinity, the result isNaN.If
x1_iis either+0or-0andx2_iis either+0or-0, the result isNaN.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis-0andx2_iis greater than0, the result is-0.If
x1_iis+0andx2_iis less than0, the result is-0.If
x1_iis-0andx2_iis less than0, the result is+0.If
x1_iis greater than0andx2_iis+0, the result is+infinity.If
x1_iis greater than0andx2_iis-0, the result is-infinity.If
x1_iis less than0andx2_iis+0, the result is-infinity.If
x1_iis less than0andx2_iis-0, the result is+infinity.If
x1_iis+infinityandx2_iis a positive (i.e., greater than0) finite number, the result is+infinity.If
x1_iis+infinityandx2_iis a negative (i.e., less than0) finite number, the result is-infinity.If
x1_iis-infinityandx2_iis a positive (i.e., greater than0) finite number, the result is-infinity.If
x1_iis-infinityandx2_iis a negative (i.e., less than0) finite number, the result is+infinity.If
x1_iis a positive (i.e., greater than0) finite number andx2_iis+infinity, the result is+0.If
x1_iis a positive (i.e., greater than0) finite number andx2_iis-infinity, the result is-0.If
x1_iis a negative (i.e., less than0) finite number andx2_iis+infinity, the result is-0.If
x1_iis a negative (i.e., less than0) finite number andx2_iis-infinity, the result is+0.If
x1_iandx2_ihave the same mathematical sign and are both nonzero finite numbers, the result has a positive mathematical sign.If
x1_iandx2_ihave different mathematical signs and are both nonzero finite numbers, the result has a negative mathematical sign.In the remaining cases, where neither
-infinity,+0,-0, norNaNis involved, the quotient must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported rounding mode. If the magnitude is too large to represent, the operation overflows and the result is aninfinityof appropriate mathematical sign. If the magnitude is too small to represent, the operation underflows and the result is a zero of appropriate mathematical sign.
For complex floating-point operands, division is defined according to the following table. For real components
aandcand imaginary componentsbandd,c
dj
c + dj
a
a / c
-(a/d)j
special rules
bj
(b/c)j
b/d
special rules
a + bj
(a/c) + (b/c)j
b/d - (a/d)j
special rules
In general, for complex floating-point operands, real-valued floating-point special cases must independently apply to the real and imaginary component operations involving real numbers as described in the above table.
When
a,b,c, ordare all finite numbers (i.e., a value other thanNaN,+infinity, or-infinity), division of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number division\[\frac{a + bj}{c + dj} = \frac{(ac + bd) + (bc - ad)j}{c^2 + d^2}\]When at least one of
a,b,c, ordisNaN,+infinity, or-infinity,If
a,b,c, anddare allNaN, the result isNaN + NaN j.In the remaining cases, the result is implementation dependent.
Note
For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is
NaN, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations.Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.eig(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns eigenvalues and eigenvectors of a real or complex matrix (or stack of matrices)
x.Let \(\mathbb{K}\) be the union of the set of real numbers \(\mathbb{R}\) and the set of complex numbers, \(\mathbb{C}\).
A real or complex value \(lambda \in \mathbb{K}\) is an eigenvalue of a real or complex matrix \(x \in \mathbb{K}^{n \times n}\) if there exists a real or complex vector \(v \in \mathbb{K}^{n}\), such that
\[x v = \lambda v\]Then, \(v\) is referred to as an eigenvector of \(x\), corresponding to the eigenvalue \(\lambda\).
A general matrix \(x \in \mathbb{K}^{n \times n}\)
has \(n\) eigenvalues, which are defined as the roots (counted with multiplicity) of the polynomial \(p\) of degree \(n\) given by
\[p(\lambda) = \operatorname{det}(x - \lambda I_n)\]does not in general have \(n\) linearly independent eigenvectors if it has eigenvalues with multiplicity larger than one.
Note
The eigenvalues of a non-symmetric real matrix are in general complex: for :math:x in mathbb{R}^{n times n}`, the eigenvalues, \(\lambda \in \mathbb{C}\), may or may not reside on the real axis of the complex plane.
Warning
The eigenvectors of a general matrix are not unique and are not continuous with respect to
x. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors.For eigenvalues of multiplity \(s=1\), the non-uniqueness stems from the fact that multiplying an eigenvector by \(-1\) when
xis real-valued and by \(e^{\phi j}\) (\(\phi \in \mathbb{R}\)) whenxis complex produces another set of valid eigenvectors.For eigenvalues of multiplity \(s > 1\), the \(s\) computed eigenvectors may be repeated or have entries differ by an order of machine epsilon for the data type of \(x\).
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – a namedtuple (
eigenvalues,eigenvectors) whosefirst element must have the field name
eigenvalues(corresponding to \(\lambda\) above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape(..., M)and must have a complex floating-point array data type having the same precision as that ofx(e.g., ifxhas afloat32data type,eigenvaluesmust have thecomplex64data type; ifxhas afloat64data type,eigenvalueshave thecomplex128data type).second element must have the field name
eigenvectors(corresponding to \(v\) above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape(..., M, M)and must have the same data type aseigenvalues.
- Return type:
Tuple[array, array]
Notes
Eigenvalue sort order is left unspecified and is thus implementation-dependent.
Note
For real symmetric or complex Hermitian matrices, prefer using the
eighroutine.Added in version 2025.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.eigh(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns an eigenvalue decomposition of a complex Hermitian or real symmetric matrix (or a stack of matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The eigenvalue decomposition of a complex Hermitian or real symmetric matrix \(x \in\ \mathbb{K}^{n \times n}\) is defined as
\[x = Q \Lambda Q^H\]with \(Q \in \mathbb{K}^{n \times n}\) and \(\Lambda \in \mathbb{R}^n\) and where \(Q^H\) is the conjugate transpose when \(Q\) is complex and the transpose when \(Q\) is real-valued and \(\Lambda\) is a diagonal matrix whose diagonal elements are the corresponding eigenvalues. When
xis real-valued, \(Q\) is orthogonal, and, whenxis complex, \(Q\) is unitary.Note
The eigenvalues of a complex Hermitian or real symmetric matrix are always real.
Warning
The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to
x. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors.Non-uniqueness stems from the fact that multiplying an eigenvector by \(-1\) when
xis real-valued and by \(e^{\phi j}\) (\(\phi \in \mathbb{R}\)) whenxis complex produces another set of valid eigenvectors.Note
Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined.
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – a namedtuple (
eigenvalues,eigenvectors) whosefirst element must have the field name
eigenvalues(corresponding to \(\operatorname{diag}\Lambda\) above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape(..., M)and must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, theneigenvaluesmust befloat64).second element must have the field name
eigenvectors(corresponding to \(Q\) above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape(..., M, M)and must have the same data type asx.
- Return type:
Tuple[array, array]
Notes
Note
Eigenvalue sort order is left unspecified and is thus implementation-dependent.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.eigvals(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the eigenvalues of a real or complex matrix (or a stack of matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the union of the set of real numbers \(\mathbb{R}\) and the set of complex numbers, \(\mathbb{C}\); ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The eigenvalues of a real or complex matrix \(x \in\ \mathbb{K}^{n \times n}\) are defined as the roots (counted with multiplicity) of the polynomial \(p\) of degree \(n\) given by
\[p(\lambda) = \operatorname{det}(x - \lambda I_n)\]where \(\lambda \in \mathbb{K}\) and where \(I_n\) is the n-dimensional identity matrix.
Note
The eigenvalues of a non-symmetric real matrix are in general complex: for :math:x in mathbb{R}^{n times n}`, the eigenvalues \(\lambda \in \mathbb{C}\), may or may not reside on the real axis of the complex plane.
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – an array containing the computed eigenvalues. The returned array must have shape
(..., M)and have a complex floating-point array data type having the same precision as that ofx(e.g., ifxhas afloat32data type, the array must have thecomplex64data type; ifxhas afloat64data type, the array has thecomplex128data type).- Return type:
array
Notes
Eigenvalue sort order is left unspecified and is thus implementation-dependent.
Added in version 2025.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.eigvalsh(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the eigenvalues of a complex Hermitian or real symmetric matrix (or a stack of matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The eigenvalues of a complex Hermitian or real symmetric matrix \(x \in\ \mathbb{K}^{n \times n}\) are defined as the roots (counted with multiplicity) of the polynomial \(p\) of degree \(n\) given by
\[p(\lambda) = \operatorname{det}(x - \lambda I_n)\]where \(\lambda \in \mathbb{R}\) and where \(I_n\) is the n-dimensional identity matrix.
Note
The eigenvalues of a complex Hermitian or real symmetric matrix are always real.
Note
Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined.
- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – an array containing the computed eigenvalues. The returned array must have shape
(..., M)and have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then must have afloat64data type).- Return type:
array
Notes
Note
Eigenvalue sort order is left unspecified and is thus implementation-dependent.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.empty(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns an uninitialized array having a specified shape.
- Parameters:
shape (Union[int, Tuple[int, ...]]) – output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array containing uninitialized data.
- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.empty_like(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns an uninitialized array with the same
shapeas an input arrayx.- Parameters:
x (array) – input array from which to derive the output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be inferred fromx. Default:None.device (Optional[device]) – device on which to place the created array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the same shape as
xand containing uninitialized data.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.equal(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the truth value of
x1_i == x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special Cases
For real-valued floating-point operands,
If
x1_iisNaNorx2_iisNaN, the result isFalse.If
x1_iis+infinityandx2_iis+infinity, the result isTrue.If
x1_iis-infinityandx2_iis-infinity, the result isTrue.If
x1_iis-0andx2_iis either+0or-0, the result isTrue.If
x1_iis+0andx2_iis either+0or-0, the result isTrue.If
x1_iis a finite number,x2_iis a finite number, andx1_iequalsx2_i, the result isTrue.In the remaining cases, the result is
False.
For complex floating-point operands, let
a = real(x1_i),b = imag(x1_i),c = real(x2_i),d = imag(x2_i), andIf
a,b,c, ordisNaN, the result isFalse.In the remaining cases, the result is the logical AND of the equality comparison between the real values
aandc(real components) and between the real valuesbandd(imaginary components), as described above for real-valued floating-point operands (i.e.,a == c AND b == d).
Note
For discussion of complex number equality, see complex-numbers.
Note
Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.exp(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the exponential function for each element
x_iof the input arrayx(eraised to the power ofx_i, whereeis the base of the natural logarithm).Note
For complex floating-point operands,
exp(conj(x))must equalconj(exp(x)).Note
The exponential function is an entire function in the complex plane and has no branch cuts.
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated exponential function result for each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is1.If
x_iis-0, the result is1.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is+0.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result is1 + 0j.If
ais a finite number andbis+infinity, the result isNaN + NaN j.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis+0, the result isinfinity + 0j.If
ais-infinityandbis a finite number, the result is+0 * cis(b).If
ais+infinityandbis a nonzero finite number, the result is+infinity * cis(b).If
ais-infinityandbis+infinity, the result is0 + 0j(signs of real and imaginary components are unspecified).If
ais+infinityandbis+infinity, the result isinfinity + NaN j(sign of real component is unspecified).If
ais-infinityandbisNaN, the result is0 + 0j(signs of real and imaginary components are unspecified).If
ais+infinityandbisNaN, the result isinfinity + NaN j(sign of real component is unspecified).If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis not equal to0, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
where
cis(v)iscos(v) + sin(v)*1j.Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.expand_dims(*args, **kwargs)[source]¶
Bases:
Protocol,GenericExpands the shape of an array by inserting a new axis of size one at the position (or positions) specified by
axis.- Parameters:
x (array) – input array.
axis (Union[int, Tuple[int, ...]]) –
axis position(s) (zero-based). If
axisis an integer,axismust be equivalent to the tuple(axis,). Ifaxisis a tuple,a valid axis position must reside on the half-open interval
[-M, M), whereM = N + len(axis)andNis the number of dimensions inx.if the i-th entry is a negative integer, the axis position of the inserted singleton dimension in the output array must be computed as
M + axis[i].each entry of
axismust resolve to a unique positive axis position.for each entry of
axis, the corresponding dimension in the expanded output array must be a singleton dimension.for the remaining dimensions of the expanded output array, the output array dimensions must correspond to the dimensions of
xin order.if provided an invalid axis position, the function must raise an exception.
- Returns:
out – an expanded output array. Must have the same data type as
x. Ifaxisis an integer, the output array must haveN + 1dimensions. Ifaxisis a tuple, the output array must haveN + len(axis)dimensions.- Return type:
array
- Raises:
IndexError – If provided an invalid
axis, anIndexErrorshould be raised.
Notes
Calling this function with a tuple of axis positions must be semantically equivalent to calling this function repeatedly with a single axis position only when the following three conditions are met:
each entry of the tuple is normalized to positive axis positions according to the number of dimensions in the expanded output array.
the normalized positive axis positions are sorted in ascending order.
the normalized positive axis positions are unique.
Changed in version 2025.12: Added support for specifying a tuple of axis positions.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.expm1(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to
exp(x)-1for each elementx_iof the input arrayx.Note
The purpose of this function is to calculate
exp(x)-1.0more accurately when x is close to zero. Accordingly, conforming implementations should avoid implementing this function as simplyexp(x)-1.0. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation.Note
For complex floating-point operands,
expm1(conj(x))must equalconj(expm1(x)).Note
The exponential function is an entire function in the complex plane and has no branch cuts.
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-1.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result is0 + 0j.If
ais a finite number andbis+infinity, the result isNaN + NaN j.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis+0, the result is+infinity + 0j.If
ais-infinityandbis a finite number, the result is+0 * cis(b) - 1.0.If
ais+infinityandbis a nonzero finite number, the result is+infinity * cis(b) - 1.0.If
ais-infinityandbis+infinity, the result is-1 + 0j(sign of imaginary component is unspecified).If
ais+infinityandbis+infinity, the result isinfinity + NaN j(sign of real component is unspecified).If
ais-infinityandbisNaN, the result is-1 + 0j(sign of imaginary component is unspecified).If
ais+infinityandbisNaN, the result isinfinity + NaN j(sign of real component is unspecified).If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis not equal to0, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
where
cis(v)iscos(v) + sin(v)*1j.Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.eye(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a two-dimensional array with ones on the
kth diagonal and zeros elsewhere.Note
An output array having a complex floating-point data type must have the value
1 + 0jalong thekth diagonal and0 + 0jelsewhere.- Parameters:
n_rows (int) – number of rows in the output array.
n_cols (Optional[int]) – number of columns in the output array. If
None, the default number of columns in the output array is equal ton_rows. Default:None.k (int) – index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and
0to the main diagonal. Default:0.dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array where all elements are equal to zero, except for the
kth diagonal, whose values are equal to one.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.fft(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the one-dimensional discrete Fourier transform.
Note
Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
ifft(fft(x)) == x), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode).- Parameters:
x (array) – input array. Should have a complex floating-point data type.
n (Optional[int]) –
number of elements over which to compute the transform along the axis (dimension) specified by
axis. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal toM.If
nis greater thanM, the axis specified byaxismust be zero-padded to sizen.If
nis less thanM, the axis specified byaxismust be trimmed to sizen.If
nequalsM, all elements along the axis specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have the same data type asxand must have the same shape asx, except for the axis specified byaxiswhich must have sizen.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.fftfreq(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the discrete Fourier transform sample frequencies.
For a Fourier transform of length
nand length unit ofd, the frequencies are described as:f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd
- Parameters:
n (int) – window length.
d (float) – sample spacing between individual samples of the Fourier transform input. Default:
1.0.dtype (Optional[dtype]) – output array data type. Must be a real-valued floating-point data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array of shape
(n,)containing the sample frequencies.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the output array have the default real-valued floating-point data type.
Changed in version 2024.12: Added
dtypekeyword argument support.- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.fftn(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the n-dimensional discrete Fourier transform.
Note
Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
ifftn(fftn(x)) == x), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode).- Parameters:
x (array) – input array. Should have a complex floating-point data type.
s (Optional[Sequence[int]]) –
number of elements over which to compute the transform along the axes (dimensions) specified by
axes. Letibe the index of then-th axis specified byaxes(i.e.,i = axes[n]) andM[i]be the size of the input array along axisi. WhensisNone, the function must setsequal to a sequence of integers such thats[i]equalsM[i]for alli.If
s[i]is greater thanM[i], axisimust be zero-padded to sizes[i].If
s[i]is less thanM[i], axisimust be trimmed to sizes[i].If
s[i]equalsM[i]or-1, all elements along axisimust be used when computing the transform.
If
sis notNone,axesmust not beNone. Default:None.axes (Optional[Sequence[int]]) –
axes (dimensions) over which to compute the transform. A valid axis in
axesmust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension).If
sis provided, the correspondingaxesto be transformed must also be provided. IfaxesisNone, the function must compute the transform over all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
where
n = prod(s)is the logical FFT size.Default:
'backward'.
- Returns:
out – an array transformed along the axes (dimensions) specified by
axes. The returned array must have the same data type asxand must have the same shape asx, except for the axes specified byaxeswhich must have sizes[i].- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.fftshift(*args, **kwargs)[source]¶
Bases:
Protocol,GenericShifts the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes (dimensions) specified by
axes.Note
out[0]is the Nyquist component only if the length of the input is even.- Parameters:
x (array) – input array. Should have a floating-point data type.
axes (Optional[Union[int, Sequence[int]]]) –
axes over which to shift. If
None, the function must shift all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.
- Returns:
out – the shifted array. The returned array must have the same data type and shape as
x.- Return type:
array
Notes
Added in version 2022.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.finfo(*args, **kwargs)[source]¶
Bases:
Protocol,GenericMachine limits for floating-point data types.
- Parameters:
type (Union[dtype, array]) –
the kind of floating-point data-type about which to get information. If complex, the information is about its component data type.
Note
Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component.
- Returns:
out – an object having the following attributes:
bits: int
number of bits occupied by the real-valued floating-point data type.
eps: float
difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard.
max: float
largest representable real-valued number.
min: float
smallest representable real-valued number.
smallest_normal: float
smallest positive real-valued floating-point number with full precision.
dtype: dtype
real-valued floating-point data type.
Added in version 2022.12.
- Return type:
finfo object
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.finfo_object(*args, **kwargs)[source]¶
Bases:
Protocol,GenericDataclass returned by finfo.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- bits: int¶
- dtype: TDtype¶
- eps: float¶
- max: float¶
- min: float¶
- smallest_normal: float¶
- class array_api._2025_12.flip(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReverses the order of elements in an array along the given axis.
- Parameters:
x (array) – input array.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis (or axes) along which to reverse elements. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. IfaxisisNone, the function must flip all input array axes. If provided more than one axis, the function must flip only the specified axes. Default:None.
- Returns:
out – an output array. The returned array must have the same data type and shape as
x. The returned array must have the same elements asx, but which are reordered relative tox.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.floor(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRounds each element
x_iof the input arrayxto the greatest (i.e., closest to+infinity) integer-valued number that is not greater thanx_i.- Parameters:
x (array) – input array. Should have a real-valued data type.
- Returns:
out – an array containing the rounded result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
If
x_iis already integer-valued, the result isx_i.
For floating-point operands,
If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iisNaN, the result isNaN.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.floor_divide(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRounds the result of dividing each element
x1_iof the input arrayx1by the respective elementx2_iof the input arrayx2to the greatest (i.e., closest to +infinity) integer-value number that is not greater than the division result.- Parameters:
x1 (Union[array, int, float]) – dividend input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – divisor input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined.
Special cases
Note
Floor division was introduced in Python via PEP 238 with the goal to disambiguate “true division” (i.e., computing an approximation to the mathematical operation of division) from “floor division” (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a
float, while the latter was computed when both operands wereints. Overloading the/operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected.To resolve this ambiguity,
/was designated for true division, and//was designated for floor division. Semantically, floor division was defined as equivalent toa // b == floor(a/b); however, special floating-point cases were left ill-defined.Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is
infinity, libraries may diverge with some choosing to strictly followfloor(a/b)and others choosing to pair//with%according to the relationb = a % b + b * (a // b). The special cases leading to divergent behavior are documented below.This specification prefers floor division to match
floor(divide(x1, x2))in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior.For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis either+infinityor-infinityandx2_iis either+infinityor-infinity, the result isNaN.If
x1_iis either+0or-0andx2_iis either+0or-0, the result isNaN.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis-0andx2_iis greater than0, the result is-0.If
x1_iis+0andx2_iis less than0, the result is-0.If
x1_iis-0andx2_iis less than0, the result is+0.If
x1_iis greater than0andx2_iis+0, the result is+infinity.If
x1_iis greater than0andx2_iis-0, the result is-infinity.If
x1_iis less than0andx2_iis+0, the result is-infinity.If
x1_iis less than0andx2_iis-0, the result is+infinity.If
x1_iis+infinityandx2_iis a positive (i.e., greater than0) finite number, the result is+infinity. (note: libraries may returnNaNto match Python behavior.)If
x1_iis+infinityandx2_iis a negative (i.e., less than0) finite number, the result is-infinity. (note: libraries may returnNaNto match Python behavior.)If
x1_iis-infinityandx2_iis a positive (i.e., greater than0) finite number, the result is-infinity. (note: libraries may returnNaNto match Python behavior.)If
x1_iis-infinityandx2_iis a negative (i.e., less than0) finite number, the result is+infinity. (note: libraries may returnNaNto match Python behavior.)If
x1_iis a positive (i.e., greater than0) finite number andx2_iis+infinity, the result is+0.If
x1_iis a positive (i.e., greater than0) finite number andx2_iis-infinity, the result is-0. (note: libraries may return-1.0to match Python behavior.)If
x1_iis a negative (i.e., less than0) finite number andx2_iis+infinity, the result is-0. (note: libraries may return-1.0to match Python behavior.)If
x1_iis a negative (i.e., less than0) finite number andx2_iis-infinity, the result is+0.If
x1_iandx2_ihave the same mathematical sign and are both nonzero finite numbers, the result has a positive mathematical sign.If
x1_iandx2_ihave different mathematical signs and are both nonzero finite numbers, the result has a negative mathematical sign.In the remaining cases, where neither
-infinity,+0,-0, norNaNis involved, the quotient must be computed and rounded to the greatest (i.e., closest to +infinity) representable integer-value number that is not greater than the division result. If the magnitude is too large to represent, the operation overflows and the result is aninfinityof appropriate mathematical sign. If the magnitude is too small to represent, the operation underflows and the result is a zero of appropriate mathematical sign.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.from_dlpack(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a new array containing the data from another (array) object with a
__dlpack__method.- Parameters:
x (object) – input (array) object.
device (Optional[device]) –
device on which to place the created array. If
deviceisNoneandxsupports DLPack, the output array must be on the same device asx. Default:None.The v2023.12 standard only mandates that a compliant library should offer a way for
from_dlpackto return an array whose underlying memory is accessible to the Python interpreter, when the correspondingdeviceis provided. If the array library does not support such cases at all, the function must raiseBufferError. If a copy must be made to enable this support butcopyis set toFalse, the function must raiseValueError.Other device kinds will be considered for standardization in a future version of this API standard.
copy (Optional[bool]) – boolean indicating whether or not to copy the input. If
True, the function must always copy. IfFalse, the function must never copy, and raiseBufferErrorin case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). IfNone, the function must reuse the existing memory buffer if possible and copy otherwise. Default:None.
- Returns:
out – an array containing the data in
x.Note
The returned array may be either a copy or a view. See data-interchange for details.
- Return type:
array
- Raises:
BufferError – The
__dlpack__and__dlpack_device__methods on the input array may raiseBufferErrorwhen the data cannot be exported as DLPack (e.g., incompatible dtype, strides, or device). It may also raise other errors when export fails for other reasons (e.g., not enough memory available to materialize the data).from_dlpackmust propagate such exceptions.AttributeError – If the
__dlpack__and__dlpack_device__methods are not present on the input array. This may happen for libraries that are never able to export their data with DLPack.ValueError – If data exchange is possible via an explicit copy but
copyis set toFalse.
Notes
See
array.__dlpack__()for implementation suggestions for from_dlpack in order to handle DLPack versioning correctly.A way to move data from two array libraries to the same device (assumed supported by both libraries) in a library-agnostic fashion is illustrated below:
def func(x, y): xp_x = x.__array_namespace__() xp_y = y.__array_namespace__() # Other functions than `from_dlpack` only work if both arrays are from the same library. So if # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: if not xp_x == xp_y: y = xp_x.from_dlpack(y, copy=True, device=x.device) # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` ...
Changed in version 2023.12: Required exceptions to address unsupported use cases.
Changed in version 2023.12: Added device and copy support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.full(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a new array having a specified
shapeand filled withfill_value.- Parameters:
shape (Union[int, Tuple[int, ...]]) – output array shape.
fill_value (Union[bool, int, float, complex]) – fill value.
dtype (Optional[dtype]) –
output array data type. If
dtypeisNone, the output array data type must be inferred fromfill_valueaccording to the following rules:If the fill value is an
int, the output array data type must be the default integer data type.If the fill value is a
float, the output array data type must be the default real-valued floating-point data type.If the fill value is a
complexnumber, the output array data type must be the default complex floating-point data type.If the fill value is a
bool, the output array must have a boolean data type. Default:None.
Note
If the
fill_valueexceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array where every element is equal to
fill_value.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.full_like(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a new array filled with
fill_valueand having the sameshapeas an input arrayx.- Parameters:
x (array) – input array from which to derive the output array shape.
fill_value (Union[bool, int, float, complex]) – fill value.
dtype (Optional[dtype]) –
output array data type. If
dtypeisNone, the output array data type must be inferred fromx. Default:None.Note
If the
fill_valueexceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined.Note
If the
fill_valuehas a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see type-promotion), behavior is unspecified and, thus, implementation-defined.device (Optional[device]) – device on which to place the created array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the same shape as
xand where every element is equal tofill_value.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.greater(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the truth value of
x1_i > x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.greater_equal(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the truth value of
x1_i >= x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.hfft(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the one-dimensional discrete Fourier transform of a signal with Hermitian symmetry.
- Parameters:
x (array) – input array. Should have a complex floating-point data type.
n (Optional[int]) –
number of elements along the transformed axis (dimension) specified by
axisin the output array. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal to2*(M-1).If
n//2+1is greater thanM, the axis of the input array specified byaxismust be zero-padded to lengthn//2+1.If
n//2+1is less thanM, the axis of the input array specified byaxismust be trimmed to sizen//2+1.If
n//2+1equalsM, all elements along the axis of the input array specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type). The returned array must have the same shape asx, except for the axis specified byaxiswhich must have sizen.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array to have a complex floating-point data type and required that the output array have a real-valued data type having the same precision as the input array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.hypot(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the square root of the sum of squares for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
The value computed by this function may be interpreted as the length of the hypotenuse of a right-angled triangle with sides of length
x1_iandx2_i, the distance of a point(x1_i, x2_i)from the origin(0, 0), or the magnitude of a complex numberx1_i + x2_i * 1j.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.The purpose of this function is to avoid underflow and overflow during intermediate stages of computation. Accordingly, conforming implementations should not use naive implementations.
Special Cases
For real-valued floating-point operands,
If
x1_iis+infinityor-infinityandx2_iis any value, includingNaN, the result is+infinity.If
x2_iis+infinityor-infinityandx1_iis any value, includingNaN, the result is+infinity.If
x1_iis either+0or-0, the result is equivalent toabs(x2_i).If
x2_iis either+0or-0, the result is equivalent toabs(x1_i).If
x1_iis a finite number orNaNandx2_iisNaN, the result isNaN.If
x2_iis a finite number orNaNandx1_iisNaN, the result isNaN.Underflow may only occur when both arguments are subnormal and the correct result is also subnormal.
For real-valued floating-point operands,
hypot(x1, x2)must equalhypot(x2, x1),hypot(x1, -x2),hypot(-x1, x2), andhypot(-x1, -x2).Note
IEEE 754-2019 requires support for subnormal (a.k.a., denormal) numbers, which are useful for supporting gradual underflow. However, hardware support for subnormal numbers is not universal, and many platforms (e.g., accelerators) and compilers support toggling denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) behavior to increase performance and to guard against timing attacks.
Accordingly, conforming implementations may vary in their support for subnormal numbers.
Added in version 2023.12.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.ifft(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the one-dimensional inverse discrete Fourier transform.
Note
Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
ifft(fft(x)) == x), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode).- Parameters:
x (array) – input array. Should have a complex floating-point data type.
n (Optional[int]) –
number of elements over which to compute the transform along the axis (dimension) specified by
axis. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal toM.If
nis greater thanM, the axis specified byaxismust be zero-padded to sizen.If
nis less thanM, the axis specified byaxismust be trimmed to sizen.If
nequalsM, all elements along the axis specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have the same data type asxand must have the same shape asx, except for the axis specified byaxiswhich must have sizen.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.ifftn(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the n-dimensional inverse discrete Fourier transform.
Note
Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
ifftn(fftn(x)) == x), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode).- Parameters:
x (array) – input array. Should have a complex floating-point data type.
s (Optional[Sequence[int]]) –
number of elements over which to compute the transform along the axes (dimensions) specified by
axes. Letibe the index of then-th axis specified byaxes(i.e.,i = axes[n]) andM[i]be the size of the input array along axisi. WhensisNone, the function must setsequal to a sequence of integers such thats[i]equalsM[i]for alli.If
s[i]is greater thanM[i], axisimust be zero-padded to sizes[i].If
s[i]is less thanM[i], axisimust be trimmed to sizes[i].If
s[i]equalsM[i]or-1, all elements along axisimust be used when computing the transform.
If
sis notNone,axesmust not beNone. Default:None.axes (Optional[Sequence[int]]) –
axes (dimensions) over which to compute the transform. A valid axis in
axesmust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension).If
sis provided, the correspondingaxesto be transformed must also be provided. IfaxesisNone, the function must compute the transform over all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.norm (Literal['backward', 'ortho', 'forward']) –
specify the normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
where
n = prod(s)is the logical FFT size.Default:
'backward'.
- Returns:
out – an array transformed along the axes (dimensions) specified by
axes. The returned array must have the same data type asxand must have the same shape asx, except for the axes specified byaxeswhich must have sizes[i].- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.ifftshift(*args, **kwargs)[source]¶
Bases:
Protocol,GenericInverse of
fftshift.Note
Although identical for even-length
x,fftshiftandifftshiftdiffer by one sample for odd-lengthx.- Parameters:
x (array) – input array. Should have a floating-point data type.
axes (Optional[Union[int, Sequence[int]]]) –
axes over which to perform the inverse shift. If
None, the function must shift all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.
- Returns:
out – the shifted array. The returned array must have the same data type and shape as
x.- Return type:
array
Notes
Added in version 2022.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.ihfft(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the one-dimensional inverse discrete Fourier transform of a signal with Hermitian symmetry.
- Parameters:
x (array) – input array. Must have a real-valued floating-point data type.
n (Optional[int]) –
number of elements over which to compute the transform along the axis (dimension) specified by
axis. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal toM.If
nis greater thanM, the axis specified byaxismust be zero-padded to sizen.If
nis less thanM, the axis specified byaxismust be trimmed to sizen.If
nequalsM, all elements along the axis specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have a complex floating-point data type whose precision matches the precision ofx(e.g., ifxisfloat64, then the returned array must have acomplex128data type). The returned array must have the same shape asx, except for the axis specified byaxiswhich must have sizen//2 + 1.- Return type:
array
Notes
Added in version 2022.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.iinfo(*args, **kwargs)[source]¶
Bases:
Protocol,GenericMachine limits for integer data types.
- Parameters:
type (Union[dtype, array]) – the kind of integer data-type about which to get information.
- Returns:
out – an object having the following attributes:
bits: int
number of bits occupied by the type.
max: int
largest representable number.
min: int
smallest representable number.
dtype: dtype
integer data type.
Added in version 2022.12.
- Return type:
iinfo object
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.iinfo_object(*args, **kwargs)[source]¶
Bases:
Protocol,GenericDataclass returned by iinfo.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- bits: int¶
- dtype: TDtype¶
- max: int¶
- min: int¶
- class array_api._2025_12.imag(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the imaginary component of a complex number for each element
x_iof the input arrayx.- Parameters:
x (array) – input array. Should have a complex floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as
x(e.g., ifxiscomplex64, the returned array must have the floating-point data typefloat32).- Return type:
array
Notes
Added in version 2022.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.inv(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the multiplicative inverse of a square matrix (or a stack of square matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The inverse matrix \(x^{-1} \in\ \mathbb{K}^{n \times n}\) of a square matrix \(x \in\ \mathbb{K}^{n \times n}\) is defined as
\[x^{-1}x = xx^{-1} = I_n\]where \(I_n\) is the n-dimensional identity matrix.
The inverse matrix exists if and only if
xis invertible. Whenxis invertible, the inverse is unique.When
xis a stack of matrices, the function must compute the inverse for each matrix in the stack.- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by type-promotion and must have the same shape as
x.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.irfft(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the one-dimensional inverse of
rfftfor complex-valued input.Note
Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
irfft(rfft(x)) == x), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms.- Parameters:
x (array) – input array. Should have a complex floating-point data type.
n (Optional[int]) –
number of elements along the transformed axis (dimension) specified by
axisin the output array. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal to2*(M-1).If
n//2+1is greater thanM, the axis of the input array specified byaxismust be zero-padded to sizen//2+1.If
n//2+1is less thanM, the axis of the input array specified byaxismust be trimmed to sizen//2+1.If
n//2+1equalsM, all elements along the axis of the input array specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type). The returned array must have the same shape asx, except for the axis specified byaxiswhich must have sizen.- Return type:
array
Notes
In order to return an array having an odd number of elements along the transformed axis, the function must be provided an odd integer for
n.
Added in version 2022.12.
Changed in version 2023.12: Required the output array have a real-valued floating-point data type having the same precision as the input array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.irfftn(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the n-dimensional inverse of
rfftnfor complex-valued input.Note
Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
irfftn(rfftn(x)) == x), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes.- Parameters:
x (array) – input array. Should have a complex floating-point data type.
s (Optional[Sequence[int]]) –
number of elements along the transformed axes (dimensions) specified by
axesin the output array. Letibe the index of then-th axis specified byaxes(i.e.,i = axes[n]) andM[i]be the size of the input array along axisi. WhensisNone, the function must setsequal to a sequence of integers such thats[i]equalsM[i]for alli, except for the last transformed axis in whichs[i]equals2*(M[i]-1). For eachi, letnequals[i], except for the last transformed axis in whichnequalss[i]//2+1.If
nis greater thanM[i], axisiof the input array must be zero-padded to sizen.If
nis less thanM[i], axisiof the input array must be trimmed to sizen.If
nequalsM[i]or-1, all elements along axisiof the input array must be used when computing the transform.
If
sis notNone,axesmust not beNone. Default:None.axes (Optional[Sequence[int]]) –
axes (dimensions) over which to compute the transform. A valid axis in
axesmust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension).If
sis provided, the correspondingaxesto be transformed must also be provided. IfaxesisNone, the function must compute the transform over all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': normalize by1/n.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': no normalization.
where
n = prod(s)is the logical FFT size.Default:
'backward'.
- Returns:
out – an array transformed along the axes (dimension) specified by
axes. The returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type). The returned array must have the same shape asx, except for the transformed axes which must have sizes[i].- Return type:
array
Notes
In order to return an array having an odd number of elements along the last transformed axis, the function must be provided an odd integer for
s[-1].
Added in version 2022.12.
Changed in version 2023.12: Required the output array have a real-valued floating-point data type having the same precision as the input array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.isdtype(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a boolean indicating whether a provided dtype is of a specified data type “kind”.
- Parameters:
dtype (dtype) – the input dtype.
kind (Union[str, dtype, Tuple[Union[str, dtype], ...]]) –
data type kind.
If
kindis a dtype, the function must return a boolean indicating whether the inputdtypeis equal to the dtype specified bykind.If
kindis a string, the function must return a boolean indicating whether the inputdtypeis of a specified data type kind. The following dtype kinds must be supported:'bool': boolean data types (e.g.,bool).'signed integer': signed integer data types (e.g.,int8,int16,int32,int64).'unsigned integer': unsigned integer data types (e.g.,uint8,uint16,uint32,uint64).'integral': integer data types. Shorthand for('signed integer', 'unsigned integer').'real floating': real-valued floating-point data types (e.g.,float32,float64).'complex floating': complex floating-point data types (e.g.,complex64,complex128).'numeric': numeric data types. Shorthand for('integral', 'real floating', 'complex floating').
If
kindis a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the inputdtypeis either equal to a specified dtype or belongs to at least one specified data type kind.
Note
A conforming implementation of the array API standard is not limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting
float16andbfloat16can includefloat16andbfloat16in thereal floatingdata type kind. Similarly, implementations supportingint128can includeint128in thesigned integerdata type kind.In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation.
- Returns:
out – boolean indicating whether a provided dtype is of a specified data type kind.
- Return type:
Notes
Added in version 2022.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.isfinite(*args, **kwargs)[source]¶
Bases:
Protocol,GenericTests each element
x_iof the input arrayxto determine if finite.- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing test results. The returned array must have a data type of
bool.- Return type:
array
Notes
Special Cases
For real-valued floating-point operands,
If
x_iis either+infinityor-infinity, the result isFalse.If
x_iisNaN, the result isFalse.If
x_iis a finite number, the result isTrue.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
aisNaNorbisNaN, the result isFalse.If
ais either+infinityor-infinityandbis any value, the result isFalse.If
ais any value andbis either+infinityor-infinity, the result isFalse.If
ais a finite number andbis a finite number, the result isTrue.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.isin(*args, **kwargs)[source]¶
Bases:
Protocol,GenericTests for each element in
x1whether the element is inx2.- Parameters:
x1 (Union[array, int]) – first input array. Should have an integer data type.
x2 (Union[array, int]) – second input array. Should have an integer data type.
invert (bool) – boolean indicating whether to invert the test criterion. If
True, the function must test whether each element inx1is not inx2. IfFalse, the function must test whether each element inx1is inx2. Default:False.
- Returns:
out – an array containing element-wise test results. The returned array must have a boolean data type. If
x1is an array, the returned array must have the same shape asx1; otherwise, the returned array must be a zero-dimensional array containing the result.- Return type:
array
Notes
At least one of
x1orx2must be an array.If an element in
x1is inx2, the corresponding element in the output array must beTrue; otherwise, the corresponding element in the output array must beFalse.Testing whether an element in
x1corresponds to an element inx2must be determined based on value equality (seeequal()).Comparison of arrays without a corresponding promotable data type (see type-promotion) is unspecified and thus implementation-defined.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.isinf(*args, **kwargs)[source]¶
Bases:
Protocol,GenericTests each element
x_iof the input arrayxto determine if equal to positive or negative infinity.- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing test results. The returned array must have a data type of
bool.- Return type:
array
Notes
Special Cases
For real-valued floating-point operands,
If
x_iis either+infinityor-infinity, the result isTrue.In the remaining cases, the result is
False.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+infinityor-infinityandbis any value (includingNaN), the result isTrue.If
ais either a finite number orNaNandbis either+infinityor-infinity, the result isTrue.In the remaining cases, the result is
False.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.isnan(*args, **kwargs)[source]¶
Bases:
Protocol,GenericTests each element
x_iof the input arrayxto determine whether the element isNaN.- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing test results. The returned array should have a data type of
bool.- Return type:
array
Notes
Special Cases
For real-valued floating-point operands,
If
x_iisNaN, the result isTrue.In the remaining cases, the result is
False.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
aorbisNaN, the result isTrue.In the remaining cases, the result is
False.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.less(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the truth value of
x1_i < x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.less_equal(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the truth value of
x1_i <= x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.linspace(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns evenly spaced numbers over a specified interval.
Let \(N\) be the number of generated values (which is either
numornum+1depending on whetherendpointisTrueorFalse, respectively). For real-valued output arrays, the spacing between values is given by\[\Delta_{\textrm{real}} = \frac{\textrm{stop} - \textrm{start}}{N - 1}\]For complex output arrays, let
a = real(start),b = imag(start),c = real(stop), andd = imag(stop). The spacing between complex values is given by\[\Delta_{\textrm{complex}} = \frac{c-a}{N-1} + \frac{d-b}{N-1} j\]- Parameters:
start (Union[int, float, complex]) – the start of the interval.
stop (Union[int, float, complex]) –
the end of the interval. If
endpointisFalse, the function must generate a sequence ofnum+1evenly spaced numbers starting withstartand ending withstopand exclude thestopfrom the returned array such that the returned array consists of evenly spaced numbers over the half-open interval[start, stop). IfendpointisTrue, the output array must consist of evenly spaced numbers over the closed interval[start, stop]. Default:True.Note
The step size changes when endpoint is False.
num (int) – number of samples. Must be a nonnegative integer value.
dtype (Optional[dtype]) –
output array data type. Should be a floating-point data type. If
dtypeisNone,if either
startorstopis acomplexnumber, the output data type must be the default complex floating-point data type.if both
startandstopare real-valued, the output data type must be the default real-valued floating-point data type.
Default:
None.Note
If
dtypeis notNone, conversion ofstartandstopshould obey type-promotion rules. Conversions not specified according to type-promotion rules may or may not be permitted by a conforming array library.device (Optional[device]) – device on which to place the created array. Default:
None.endpoint (bool) – boolean indicating whether to include
stopin the interval. Default:True.
- Returns:
out – a one-dimensional array containing evenly spaced values.
- Return type:
array
Notes
Note
While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable.
Note
As mixed data type promotion is implementation-defined, behavior when
startorstopexceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception.Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.log(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the natural (base
e) logarithm for each elementx_iof the input arrayx.Note
The natural logarithm of a complex number \(z\) with polar coordinates \((r,\theta)\) equals \(\ln r + (\theta + 2n\pi)j\) with principal value \(\ln r + \theta j\).
Note
For complex floating-point operands,
log(conj(x))must equalconj(log(x)).Note
By convention, the branch cut of the natural logarithm is the negative real axis \((-\infty, 0)\).
The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component.
Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval \([-\pi j, +\pi j]\) along the imaginary axis and mathematically unbounded along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated natural logarithm for each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than0, the result isNaN.If
x_iis either+0or-0, the result is-infinity.If
x_iis1, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais-0andbis+0, the result is-infinity + πj.If
ais+0andbis+0, the result is-infinity + 0j.If
ais a finite number andbis+infinity, the result is+infinity + πj/2.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais-infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + πj.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0j.If
ais-infinityandbis+infinity, the result is+infinity + 3πj/4.If
ais+infinityandbis+infinity, the result is+infinity + πj/4.If
ais either+infinityor-infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is+infinity + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.log10(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the base
10logarithm for each elementx_iof the input arrayx.Note
For complex floating-point operands,
log10(conj(x))must equalconj(log10(x)).- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated base
10logarithm for each element inx. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than0, the result isNaN.If
x_iis either+0or-0, the result is-infinity.If
x_iis1, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula
\[\log_{10} x = \frac{\log_{e} x}{\log_{e} 10}\]where \(\log_{e}\) is the natural logarithm, as implemented by
log().Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.log1p(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to
log(1+x), wherelogrefers to the natural (basee) logarithm, for each elementx_iof the input arrayx.Note
The purpose of this function is to calculate
log(1+x)more accurately when x is close to zero. Accordingly, conforming implementations should avoid implementing this function as simplylog(1+x). See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation.Note
For complex floating-point operands,
log1p(conj(x))must equalconj(log1p(x)).Note
By convention, the branch cut of the natural logarithm is the negative real axis \((-\infty, 0)\).
The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component.
Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval \([-\pi j, +\pi j]\) along the imaginary axis and mathematically unbounded along the real axis.
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than-1, the result isNaN.If
x_iis-1, the result is-infinity.If
x_iis-0, the result is-0.If
x_iis+0, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais-1andbis+0, the result is-infinity + 0j.If
ais a finite number andbis+infinity, the result is+infinity + πj/2.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
ais-infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + πj.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0j.If
ais-infinityandbis+infinity, the result is+infinity + 3πj/4.If
ais+infinityandbis+infinity, the result is+infinity + πj/4.If
ais either+infinityor-infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis a finite number, the result isNaN + NaN j.If
aisNaNandbis+infinity, the result is+infinity + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.log2(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the base
2logarithm for each elementx_iof the input arrayx.Note
For complex floating-point operands,
log2(conj(x))must equalconj(log2(x)).- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the evaluated base
2logarithm for each element inx. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than0, the result isNaN.If
x_iis either+0or-0, the result is-infinity.If
x_iis1, the result is+0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula
\[\log_{2} x = \frac{\log_{e} x}{\log_{e} 2}\]where \(\log_{e}\) is the natural logarithm, as implemented by
log().Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.logaddexp(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the logarithm of the sum of exponentiations
log(exp(x1) + exp(x2))for each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis+infinityandx2_iis notNaN, the result is+infinity.If
x1_iis notNaNandx2_iis+infinity, the result is+infinity.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.logical_and(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the logical AND for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of
False, while non-zeros must be considered the equivalent ofTrue.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of bool.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.logical_not(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the logical NOT for each element
x_iof the input arrayx.Note
While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of
False, while non-zeros must be considered the equivalent ofTrue.- Parameters:
x (array) – input array. Should have a boolean data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.logical_or(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the logical OR for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of
False, while non-zeros must be considered the equivalent ofTrue.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.logical_xor(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the logical XOR for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of
False, while non-zeros must be considered the equivalent ofTrue.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.matmul(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the matrix product.
- Parameters:
x1 (array) –
first input array. Should have a numeric data type. Must have at least one dimension.
If
x1is a one-dimensional array having shape(M,)andx2has more than one dimension,x1must be promoted to a two-dimensional array by prepending1to its dimensions (i.e., must have shape(1, M)). After matrix multiplication, the prepended dimensions in the returned array must be removed.If
x1has more than one dimension (including after vector-to-matrix promotion),shape(x1)[:-2]must be compatible withshape(x2)[:-2](after vector-to-matrix promotion) (see broadcasting).If
x1has shape(..., M, K), the innermost two dimensions form matrices on which to perform matrix multiplication.
x2 (array) –
second input array. Should have a numeric data type. Must have at least one dimension.
If
x2is one-dimensional array having shape(N,)andx1has more than one dimension,x2must be promoted to a two-dimensional array by appending1to its dimensions (i.e., must have shape(N, 1)). After matrix multiplication, the appended dimensions in the returned array must be removed.If
x2has more than one dimension (including after vector-to-matrix promotion),shape(x2)[:-2]must be compatible withshape(x1)[:-2](after vector-to-matrix promotion) (see broadcasting).If
x2has shape(..., K, N), the innermost two dimensions form matrices on which to perform matrix multiplication.
- Returns:
out – output array.
If both
x1andx2are one-dimensional arrays having shape(N,), the returned array must be a zero-dimensional array and must contain the inner product as its only element.If
x1is a two-dimensional array having shape(M, K)andx2is a two-dimensional array having shape(K, N), the returned array must be a two-dimensional array and must contain the conventional matrix product and having shape(M, N).If
x1is a one-dimensional array having shape(K,)andx2is an array having shape(..., K, N), the returned array must be an array having shape(..., N)(i.e., prepended dimensions during vector-to-matrix promotion must be removed) and must contain the conventional matrix product.If
x1is an array having shape(..., M, K)andx2is a one-dimensional array having shape(K,), the returned array must be an array having shape(..., M)(i.e., appended dimensions during vector-to-matrix promotion must be removed) and must contain the conventional matrix product.If
x1is a two-dimensional array having shape(M, K)andx2is an array having shape(..., K, N), the returned array must be an array having shape(..., M, N)and must contain the conventional matrix product for each stacked matrix.If
x1is an array having shape(..., M, K)andx2is a two-dimensional array having shape(K, N), the returned array must be an array having shape(..., M, N)and must contain the conventional matrix product for each stacked matrix.If either
x1orx2has more than two dimensions, the returned array must be an array having a shape determined by broadcastingshape(x1)[:-2]againstshape(x2)[:-2]and must contain the conventional matrix product for each stacked matrix.
The returned array must have a data type determined by type-promotion.
- Return type:
array
- Raises:
Exception – an exception should be raised in the following circumstances: - if either
x1orx2is a zero-dimensional array. - ifx1is a one-dimensional array having shape(K,),x2is a one-dimensional array having shape(L,), andK != L. - ifx1is a one-dimensional array having shape(K,),x2is an array having shape(..., L, N), andK != L. - ifx1is an array having shape(..., M, K),x2is a one-dimensional array having shape(L,), andK != L. - ifx1is an array having shape(..., M, K),x2is an array having shape(..., L, N), andK != L.
Notes
The
matmulfunction must implement the same semantics as the built-in@operator (see PEP 465).If either
x1orx2has a complex floating-point data type, the function must not complex-conjugate or tranpose either argument. If conjugation and/or transposition is desired, a user can explicitly perform these operations prior to computing the matrix product.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.matrix_norm(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the matrix norm of a matrix (or a stack of matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices. Should have a floating-point data type.keepdims (bool) – If
True, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the last two axes (dimensions) must not be included in the result. Default:False.ord (Optional[Union[int, float, Literal[inf, -inf, 'fro', 'nuc']]]) –
order of the norm. The following mathematical norms must be supported:
ord
description
’fro’
Frobenius norm
’nuc’
nuclear norm
1
max(sum(abs(x), axis=0))
2
largest singular value
inf
max(sum(abs(x), axis=1))
The following non-mathematical “norms” must be supported:
ord
description
-1
min(sum(abs(x), axis=0))
-2
smallest singular value
-inf
min(sum(abs(x), axis=1))
If
ord=1, the norm corresponds to the induced matrix norm wherep=1(i.e., the maximum absolute value column sum).If
ord=2, the norm corresponds to the induced matrix norm wherep=inf(i.e., the maximum absolute value row sum).If
ord=inf, the norm corresponds to the induced matrix norm wherep=2(i.e., the largest singular value).Default:
'fro'.
- Returns:
out – an array containing the norms for each
MxNmatrix. IfkeepdimsisFalse, the returned array must have a rank which is two less than the rank ofx. Ifxhas a real-valued data type, the returned array must have a real-valued floating-point data type determined by type-promotion. Ifxhas a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.matrix_power(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRaises a square matrix (or a stack of square matrices)
xto an integer powern.- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.n (int) – integer exponent.
- Returns:
out – if
nis equal to zero, an array containing the identity matrix for each square matrix. Ifnis less than zero, an array containing the inverse of each square matrix raised to the absolute value ofn, provided that each square matrix is invertible. Ifnis greater than zero, an array containing the result of raising each square matrix to the powern. The returned array must have the same shape asxand a floating-point data type determined by type-promotion.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.matrix_rank(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the rank (i.e., number of non-zero singular values) of a matrix (or a stack of matrices).
When
xis a stack of matrices, the function must compute the number of non-zero singular values for each matrix in the stack.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices. Should have a floating-point data type.rtol (Optional[Union[float, array]]) – relative tolerance for small singular values. Singular values approximately less than or equal to
rtol * largest_singular_valueare set to zero. If afloat, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by type-promotion (as applied tox) and must be broadcast against each matrix. If anarray, must have a real-valued floating-point data type and must be compatible withshape(x)[:-2](see broadcasting). IfNone, the default value ismax(M, N) * eps, whereepsmust be the machine epsilon associated with the real-valued floating-point data type determined by type-promotion (as applied tox). Default:None.
- Returns:
out – an array containing the ranks. The returned array must have the default integer data type and must have shape
(...)(i.e., must have a shape equal toshape(x)[:-2]).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.matrix_transpose(*args, **kwargs)[source]¶
Bases:
Protocol,GenericTransposes a matrix (or a stack of matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices.- Returns:
out – an array containing the transpose for each matrix. The returned array must have shape
(..., N, M). The returned array must have the same data type asx.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.max(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the maximum value of the input array
x.- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute maximum values. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the maximum value is computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as
x.- Return type:
array
Notes
When the number of elements over which to compute the maximum value is zero, the maximum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if
xis a floating-point input array, returnNaN), or return the minimum possible value for the input arrayxdata type (e.g., ifxis a floating-point array, return-infinity).The order of signed zeros is unspecified and thus implementation-defined. When choosing between
-0or+0as a maximum value, specification-compliant libraries may choose to return either value.For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see complex-number-ordering).
Special Cases
For floating-point operands,
If
x_iisNaN, the maximum value must beNaN(i.e.,NaNvalues propagate).
Changed in version 2023.12: Clarified that the order of signed zeros is implementation-defined.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.maximum(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the maximum value for each element
x1_iof the input arrayx1relative to the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise maximum values. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.The order of signed zeros is unspecified and thus implementation-defined. When choosing between
-0or+0as a maximum value, specification-compliant libraries may choose to return either value.For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see complex-number-ordering).
Special Cases
For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.
Added in version 2023.12.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.mean(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the arithmetic mean of the input array
x.- Parameters:
x (array) – input array. Should have a floating-point data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute arithmetic means. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the arithmetic mean is computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as
x.- Return type:
array
Notes
While this specification recommends that this function only accept input arrays having a floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array
xhas an integer data type, the returned array must have the default real-valued floating-point data type.
Special Cases
Let
Mequal the number of elements over which to compute the arithmetic mean. For real-valued operands,If
Mis0, the arithmetic mean must beNaN.If
x_iisNaN, the arithmetic mean must beNaN(i.e.,NaNvalues propagate).
For complex floating-point operands, real-valued floating-point special cases should independently apply to the real and imaginary component operations involving real numbers. For example, let
a = real(x_i)andb = imag(x_i), andIf
Mis0, the arithmetic mean must beNaN + NaN j.If
aisNaN, the real component of the result must beNaN.Similarly, if
bisNaN, the imaginary component of the result must beNaN.
Note
Array libraries, such as NumPy, PyTorch, and JAX, currently deviate from this specification in their handling of components which are
NaNwhen computing the arithmetic mean. In general, consumers of array libraries implementing this specification are recommended to useisnan()to test whether the result of computing the arithmetic mean over an array have a complex floating-point data type isNaN, rather than relying onNaNpropagation of individual components.Changed in version 2024.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.meshgrid(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns coordinate matrices from coordinate vectors.
- Parameters:
arrays (array) – an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type.
indexing (Literal["xy", "ij"]) – Cartesian
'xy'or matrix'ij'indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), theindexingkeyword has no effect and should be ignored. Default:'xy'.
- Returns:
out – tuple of N arrays, where
Nis the number of provided one-dimensional input arrays. Each returned array must have rankN. ForNone-dimensional arrays having lengthsNi = len(xi),if matrix indexing
ij, then each returned array must have the shape(N1, N2, N3, ..., Nn).if Cartesian indexing
xy, then each returned array must have shape(N2, N1, N3, ..., Nn).
Accordingly, for the two-dimensional case with input one-dimensional arrays of length
MandN, if matrix indexingij, then each returned array must have shape(M, N), and, if Cartesian indexingxy, then each returned array must have shape(N, M).Similarly, for the three-dimensional case with input one-dimensional arrays of length
M,N, andP, if matrix indexingij, then each returned array must have shape(M, N, P), and, if Cartesian indexingxy, then each returned array must have shape(N, M, P).Each returned array should have the same data type as the input arrays.
- Return type:
Tuple[array, …]
Notes
Changed in version 2022.12: Added complex data type support.
Changed in version 2025.12: Changed the return value from a List to a Tuple.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.min(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the minimum value of the input array
x.- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute minimum values. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the minimum value is computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as
x.- Return type:
array
Notes
When the number of elements over which to compute the minimum value is zero, the minimum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if
xis a floating-point input array, returnNaN), or return the maximum possible value for the input arrayxdata type (e.g., ifxis a floating-point array, return+infinity).The order of signed zeros is unspecified and thus implementation-defined. When choosing between
-0or+0as a minimum value, specification-compliant libraries may choose to return either value.For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see complex-number-ordering).
Special Cases
For floating-point operands,
If
x_iisNaN, the minimum value must beNaN(i.e.,NaNvalues propagate).
Changed in version 2023.12: Clarified that the order of signed zeros is implementation-defined.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.minimum(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the minimum value for each element
x1_iof the input arrayx1relative to the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise minimum values. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.The order of signed zeros is unspecified and thus implementation-defined. When choosing between
-0or+0as a minimum value, specification-compliant libraries may choose to return either value.For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see complex-number-ordering).
Special Cases
For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.
Added in version 2023.12.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.moveaxis(*args, **kwargs)[source]¶
Bases:
Protocol,GenericMoves array axes to new positions, while leaving other axes in their original positions.
- Parameters:
x (array) – input array.
source (Union[int, Tuple[int, ...]]) – axis (or axes) to move. Provided source axes must be unique. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.destination (Union[int, Tuple[int, ...]]) – axis (or axes) defining the desired position(s) for each respective
sourceaxis index. Provided destination axes must be unique. A valid axis must be an integer on the interval[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.
- Returns:
out – an array containing reordered axes. The returned array must have the same data type as
x.- Return type:
array
Notes
Added in version 2023.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.multiply(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the product for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.Note
Floating-point multiplication is not always associative due to finite precision.
- Parameters:
x1 (Union[array, int, float, complex]) – first input array. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – second input array. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise products. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For real-valued floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis either+infinityor-infinityandx2_iis either+0or-0, the result isNaN.If
x1_iis either+0or-0andx2_iis either+infinityor-infinity, the result isNaN.If
x1_iandx2_ihave the same mathematical sign, the result has a positive mathematical sign, unless the result isNaN. If the result isNaN, the “sign” ofNaNis implementation-defined.If
x1_iandx2_ihave different mathematical signs, the result has a negative mathematical sign, unless the result isNaN. If the result isNaN, the “sign” ofNaNis implementation-defined.If
x1_iis either+infinityor-infinityandx2_iis either+infinityor-infinity, the result is a signed infinity with the mathematical sign determined by the rule already stated above.If
x1_iis either+infinityor-infinityandx2_iis a nonzero finite number, the result is a signed infinity with the mathematical sign determined by the rule already stated above.If
x1_iis a nonzero finite number andx2_iis either+infinityor-infinity, the result is a signed infinity with the mathematical sign determined by the rule already stated above.In the remaining cases, where neither
infinitynorNaNis involved, the product must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported rounding mode. If the magnitude is too large to represent, the result is an infinity of appropriate mathematical sign. If the magnitude is too small to represent, the result is a zero of appropriate mathematical sign.
For complex floating-point operands, multiplication is defined according to the following table. For real components
aandcand imaginary componentsbandd,c
dj
c + dj
a
a * c
(a*d)j
(a*c) + (a*d)j
bj
(b*c)j
-(b*d)
-(b*d) + (b*c)j
a + bj
(a*c) + (b*c)j
-(b*d) + (a*d)j
special rules
In general, for complex floating-point operands, real-valued floating-point special cases must independently apply to the real and imaginary component operations involving real numbers as described in the above table.
When
a,b,c, ordare all finite numbers (i.e., a value other thanNaN,+infinity, or-infinity), multiplication of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number multiplication\[(a + bj) \cdot (c + dj) = (ac - bd) + (bc + ad)j\]When at least one of
a,b,c, ordisNaN,+infinity, or-infinity,If
a,b,c, anddare allNaN, the result isNaN + NaN j.In the remaining cases, the result is implementation dependent.
Note
For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is
NaN, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations.Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.negative(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the numerical negative of each element
x_i(i.e.,y_i = -x_i) of the input arrayx.Note
For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent.
Note
If
xhas a complex floating-point data type, both the real and imaginary components for eachx_imust be negated (a result which follows from the rules of complex number multiplication).- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.nextafter(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the next representable floating-point value for each element
x1_iof the input arrayx1in the direction of the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float]) – first input array. Should have a real-valued floating-point data type.
x2 (Union[array, int, float]) – second input array. Must be compatible with
x1(see broadcasting). Should have the same data type asx1.
- Returns:
out – an array containing the element-wise results. The returned array must have the same data type as
x1.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special cases
For real-valued floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis-0andx2_iis+0, the result is+0.If
x1_iis+0andx2_iis-0, the result is-0.
Added in version 2024.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.nonzero(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the indices of the array elements which are non-zero.
Data-dependent output shape
The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. Must have one or more dimensions. If
xis zero-dimensional, the function must raise an exception.- Returns:
out – a tuple of
karrays, one for each dimension ofxand each of sizen(wherenis the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must be returned in row-major, C-style order. The returned array must have the default array index data type.- Return type:
Tuple[array, …]
Notes
If
xhas a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero.If
xhas a boolean data type, non-zero elements are those elements which are equal toTrue.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.not_equal(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the truth value of
x1_i != x2_ifor each elementx1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
- Returns:
out – an array containing the element-wise results. The returned array must have a data type of
bool.- Return type:
array
Notes
At least one of
x1orx2must be an array.
Special Cases
For real-valued floating-point operands,
If
x1_iisNaNorx2_iisNaN, the result isTrue.If
x1_iis+infinityandx2_iis-infinity, the result isTrue.If
x1_iis-infinityandx2_iis+infinity, the result isTrue.If
x1_iis a finite number,x2_iis a finite number, andx1_idoes not equalx2_i, the result isTrue.In the remaining cases, the result is
False.
For complex floating-point operands, let
a = real(x1_i),b = imag(x1_i),c = real(x2_i),d = imag(x2_i), andIf
a,b,c, ordisNaN, the result isTrue.In the remaining cases, the result is the logical OR of the equality comparison between the real values
aandc(real components) and between the real valuesbandd(imaginary components), as described above for real-valued floating-point operands (i.e.,a != c OR b != d).
Note
For discussion of complex number equality, see complex-numbers.
Note
Comparison of arrays without a corresponding promotable data type (see type-promotion) is undefined and thus implementation-dependent.
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Cross-kind comparisons are explicitly left unspecified.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.ones(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a new array having a specified
shapeand filled with ones.Note
An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e.,
1 + 0j).- Parameters:
shape (Union[int, Tuple[int, ...]]) – output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array containing ones.
- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.ones_like(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a new array filled with ones and having the same
shapeas an input arrayx.Note
An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e.,
1 + 0j).- Parameters:
x (array) – input array from which to derive the output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be inferred fromx. Default:None.device (Optional[device]) – device on which to place the created array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the same shape as
xand filled with ones.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.outer(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the outer product of two vectors
x1andx2.- Parameters:
x1 (array) – first one-dimensional input array of size
N. Must have a numeric data type.x2 (array) – second one-dimensional input array of size
M. Must have a numeric data type.
- Returns:
out – a two-dimensional array containing the outer product and whose shape is
(N, M). The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.permute_dims(*args, **kwargs)[source]¶
Bases:
Protocol,GenericPermutes the axes of an array
x.- Parameters:
x (array) – input array.
axes (Tuple[int, ...]) – tuple containing a permutation of axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the respective axis index by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.
- Returns:
out – an array containing the axes permutation. The returned array must have the same data type as
x.- Return type:
array
Notes
Changed in version 2025.12: Added support for negative axes.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.pinv(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the (Moore-Penrose) pseudo-inverse of a matrix (or a stack of matrices)
x.The pseudo-inverse of a matrix \(A\), denoted \(A^{+}\), is defined as the matrix that “solves” the least-squares problem \(Ax = b\) (i.e., if \(\overline{x}\) is a solution, then \(A^{+}\) is the matrix such that \(\overline{x} = A^{+}b\)).
While the pseudo-inverse can be defined algebraically, one can understand the pseudo-inverse via singular value decomposition (SVD). Namely, if
\[A = U \Sigma V^H\]is a singular decomposition of \(A\), then
\[A^{+} = U \Sigma^{+} V^H\]where \(U\) and \(V^H\) are orthogonal matrices, \(\Sigma\) is a diagonal matrix consisting of \(A\)’s singular values, and \(\Sigma^{+}\) is then a diagonal matrix consisting of the reciprocals of \(A\)’s singular values, leaving zeros in place. During numerical computation, only elements larger than a small tolerance are considered nonzero, and all others replaced by zeros.
When
xis a stack of matrices, the function must compute the pseudo-inverse for each matrix in the stack.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices. Should have a floating-point data type.rtol (Optional[Union[float, array]]) – relative tolerance for small singular values. Singular values approximately less than or equal to
rtol * largest_singular_valueare set to zero. If afloat, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by type-promotion (as applied tox) and must be broadcast against each matrix. If anarray, must have a real-valued floating-point data type and must be compatible withshape(x)[:-2](see broadcasting). IfNone, the default value ismax(M, N) * eps, whereepsmust be the machine epsilon associated with the real-valued floating-point data type determined by type-promotion (as applied tox). Default:None.
- Returns:
out – an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by type-promotion and must have shape
(..., N, M)(i.e., must have the same shape asx, except the innermost two dimensions must be transposed).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.positive(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the numerical positive of each element
x_i(i.e.,y_i = +x_i) of the input arrayx.- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.pow(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation of exponentiation by raising each element
x1_i(the base) of the input arrayx1to the power ofx2_i(the exponent), wherex2_iis the corresponding element of the input arrayx2.- Parameters:
x1 (Union[array, int, float, complex]) – first input array whose elements correspond to the exponentiation base. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – second input array whose elements correspond to the exponentiation exponent. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.If both
x1andx2have integer data types, the result ofpowwhenx2_iis negative (i.e., less than zero) is unspecified and thus implementation-dependent.If
x1has an integer data type andx2has a floating-point data type, behavior is implementation-dependent (type promotion between data type “kinds” (integer versus floating-point) is unspecified).By convention, the branch cut of the natural logarithm is the negative real axis \((-\infty, 0)\).
The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to
exp(x2*log(x1)), exponentiation has the same branch cut forx1as the natural logarithm (seelog()).Note: branch cuts follow C99 and have provisional status (see branch-cuts).
Special cases
For real-valued floating-point operands,
If
x1_iis not equal to1andx2_iisNaN, the result isNaN.If
x2_iis+0, the result is1, even ifx1_iisNaN.If
x2_iis-0, the result is1, even ifx1_iisNaN.If
x1_iisNaNandx2_iis not equal to0, the result isNaN.If
abs(x1_i)is greater than1andx2_iis+infinity, the result is+infinity.If
abs(x1_i)is greater than1andx2_iis-infinity, the result is+0.If
abs(x1_i)is1andx2_iis+infinity, the result is1.If
abs(x1_i)is1andx2_iis-infinity, the result is1.If
x1_iis1andx2_iis notNaN, the result is1.If
abs(x1_i)is less than1andx2_iis+infinity, the result is+0.If
abs(x1_i)is less than1andx2_iis-infinity, the result is+infinity.If
x1_iis+infinityandx2_iis greater than0, the result is+infinity.If
x1_iis+infinityandx2_iis less than0, the result is+0.If
x1_iis-infinity,x2_iis greater than0, andx2_iis an odd integer value, the result is-infinity.If
x1_iis-infinity,x2_iis greater than0, andx2_iis not an odd integer value, the result is+infinity.If
x1_iis-infinity,x2_iis less than0, andx2_iis an odd integer value, the result is-0.If
x1_iis-infinity,x2_iis less than0, andx2_iis not an odd integer value, the result is+0.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis+0andx2_iis less than0, the result is+infinity.If
x1_iis-0,x2_iis greater than0, andx2_iis an odd integer value, the result is-0.If
x1_iis-0,x2_iis greater than0, andx2_iis not an odd integer value, the result is+0.If
x1_iis-0,x2_iis less than0, andx2_iis an odd integer value, the result is-infinity.If
x1_iis-0,x2_iis less than0, andx2_iis not an odd integer value, the result is+infinity.If
x1_iis less than0,x1_iis a finite number,x2_iis a finite number, andx2_iis not an integer value, the result isNaN.
For complex floating-point operands, special cases should be handled as if the operation is implemented as
exp(x2*log(x1)).Note
Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification.
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.prod(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the product of input array
xelements.- Parameters:
x (array) – input array. Should have a numeric data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute products. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the sum (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the product is computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the
dtypeparameter above.- Return type:
array
Notes
Special Cases
Let
Mequal the number of elements over which to compute the product.If
Mis0, the product must be 1 (i.e., the empty product).
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
multiply().Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.qr(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the QR decomposition of a full column rank matrix (or a stack of matrices).
If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The complete QR decomposition of a matrix \(x \in\ \mathbb{K}^{n \times n}\) is defined as
\[x = QR\]where \(Q \in\ \mathbb{K}^{m \times m}\) is orthogonal when
xis real-valued and unitary whenxis complex-valued and where \(R \in\ \mathbb{K}^{m \times n}\) is an upper triangular matrix with real diagonal (even whenxis complex-valued).When \(m \gt n\) (tall matrix), as \(R\) is upper triangular, the last \(m - n\) rows are zero. In this case, the last \(m - n\) columns of \(Q\) can be dropped to form the reduced QR decomposition.
\[x = QR\]where \(Q \in\ \mathbb{K}^{m \times n}\) and \(R \in\ \mathbb{K}^{n \times n}\).
The reduced QR decomposition equals with the complete QR decomposition when \(n \geq m\) (wide matrix).
When
xis a stack of matrices, the function must compute the QR decomposition for each matrix in the stack.Note
Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined.
Warning
The elements in the diagonal of \(R\) are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of \(R\), and different libraries or inputs on different devices may produce different valid decompositions.
Warning
The QR decomposition is only well-defined if the first
k = min(m,n)columns of every matrix inxare linearly independent.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices of rankN. Should have a floating-point data type.mode (Literal['reduced', 'complete']) –
decomposition mode. Should be one of the following modes:
'reduced': compute only the leadingKcolumns ofq, such thatqandrhave dimensions(..., M, K)and(..., K, N), respectively, and whereK = min(M, N).'complete': computeqandrwith dimensions(..., M, M)and(..., M, N), respectively.
Default:
'reduced'.
- Returns:
out – a namedtuple
(Q, R)whosefirst element must have the field name
Qand must be an array whose shape depends on the value ofmodeand contain matrices with orthonormal columns. Ifmodeis'complete', the array must have shape(..., M, M). Ifmodeis'reduced', the array must have shape(..., M, K), whereK = min(M, N). The firstx.ndim-2dimensions must have the same size as those of the input arrayx.second element must have the field name
Rand must be an array whose shape depends on the value ofmodeand contain upper-triangular matrices. Ifmodeis'complete', the array must have shape(..., M, N). Ifmodeis'reduced', the array must have shape(..., K, N), whereK = min(M, N). The firstx.ndim-2dimensions must have the same size as those of the inputx.
Each returned array must have a floating-point data type determined by type-promotion.
- Return type:
Tuple[array, array]
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.real(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the real component of a complex number for each element
x_iof the input arrayx.- Parameters:
x (array) – input array. Must have a numeric data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as
x(e.g., ifxiscomplex64, the returned array must have the floating-point data typefloat32).- Return type:
array
Notes
Whether the returned array and the input array share the same underlying memory is unspecified and thus implementation-defined.
Added in version 2022.12.
Changed in version 2024.12: Added support for real-valued arrays.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.reciprocal(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the reciprocal for each element
x_iof the input arrayx.- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the element-wise results. The returned array must have a floating-point data type determined by type-promotion.
- Return type:
array
Notes
Special cases
For floating-point operands, special cases must be handled as if the operation is implemented as
1.0 / x(seedivide()).Added in version 2024.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.remainder(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the remainder of division for each element
x1_iof the input arrayx1and the respective elementx2_iof the input arrayx2.Note
This function is equivalent to the Python modulus operator
x1_i % x2_i.- Parameters:
x1 (Union[array, int, float]) – dividend input array. Should have a real-valued data type.
x2 (Union[array, int, float]) – divisor input array. Must be compatible with
x1(see broadcasting). Should have a real-valued data type.
- Returns:
out – an array containing the element-wise results. Each element-wise result must have the same sign as the respective element
x2_i. The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
At least one of
x1orx2must be an array.For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined.
Special cases
Note
In general, similar to Python’s
%operator, this function is not recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility.For floating-point operands,
If either
x1_iorx2_iisNaN, the result isNaN.If
x1_iis either+infinityor-infinityandx2_iis either+infinityor-infinity, the result isNaN.If
x1_iis either+0or-0andx2_iis either+0or-0, the result isNaN.If
x1_iis+0andx2_iis greater than0, the result is+0.If
x1_iis-0andx2_iis greater than0, the result is+0.If
x1_iis+0andx2_iis less than0, the result is-0.If
x1_iis-0andx2_iis less than0, the result is-0.If
x1_iis greater than0andx2_iis+0, the result isNaN.If
x1_iis greater than0andx2_iis-0, the result isNaN.If
x1_iis less than0andx2_iis+0, the result isNaN.If
x1_iis less than0andx2_iis-0, the result isNaN.If
x1_iis+infinityandx2_iis a positive (i.e., greater than0) finite number, the result isNaN.If
x1_iis+infinityandx2_iis a negative (i.e., less than0) finite number, the result isNaN.If
x1_iis-infinityandx2_iis a positive (i.e., greater than0) finite number, the result isNaN.If
x1_iis-infinityandx2_iis a negative (i.e., less than0) finite number, the result isNaN.If
x1_iis a positive (i.e., greater than0) finite number andx2_iis+infinity, the result isx1_i. (note: this result matches Python behavior.)If
x1_iis a positive (i.e., greater than0) finite number andx2_iis-infinity, the result isx2_i. (note: this result matches Python behavior.)If
x1_iis a negative (i.e., less than0) finite number andx2_iis+infinity, the result isx2_i. (note: this results matches Python behavior.)If
x1_iis a negative (i.e., less than0) finite number andx2_iis-infinity, the result isx1_i. (note: this result matches Python behavior.)In the remaining cases, the result must match that of the Python
%operator.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.repeat(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRepeats each element of an array a specified number of times on a per-element basis.
Data-dependent output shape
When
repeatsis an array, the shape of the output array for this function depends on the data values in therepeatsarray; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing the values inrepeats. Accordingly, such libraries may choose to omit support forrepeatsarrays; however, conforming implementations must support providing a literalint. See data-dependent-output-shapes section for more details.- Parameters:
x (array) – input array containing elements to repeat.
repeats (Union[int, array]) –
the number of repetitions for each element.
If
axisisNone, letM = prod(x.shape)andif
repeatsis an array,repeatsmust be broadcast compatible with the shape(M,)(i.e., be a one-dimensional array having shape(1,)or(M,)).if
repeatsis an integer,repeatsmust be broadcasted to the shape (M,).
If
axisis notNone, letS = x.shape[axis]andif
repeatsis an array,repeatsmust be broadcast compatible with the shape(S,)(i.e., be a one-dimensional array having shape(1,)or(S,)).if
repeatsis an integer,repeatsmust be broadcasted to the shape(S,).
If
repeatsis an array, the array must have an integer data type.axis (Optional[int]) – the axis along which to repeat elements. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Ifaxisis None, the function must flatten the input arrayxand then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array must be flattened in row-major, C-style order. Default:None.
- Returns:
out – an output array containing repeated elements. The returned array must have the same data type as
x. IfaxisisNone, the returned array must be a one-dimensional array; otherwise, the returned array must have the same shape asx, except for the axis along which elements were repeated.- Return type:
array
Notes
For specification-conforming array libraries supporting hardware acceleration, providing an array for
repeatscan cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries should include a warning in their documentation regarding potential performance degradation whenrepeatsis an array.
Added in version 2023.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.reshape(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReshapes an array without changing its data.
- Parameters:
x (array) – input array to reshape.
shape (Tuple[int, ...]) – a new shape compatible with the original shape. Only one shape dimension must be allowed to be
-1. When a shape dimension is-1, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions.copy (Optional[bool]) – whether or not to copy the input array. If
True, the function must always copy (see copy-keyword-argument). IfFalse, the function must never copy. IfNone, the function must avoid copying, if possible, and may copy otherwise. Default:None.
- Returns:
out – an output array. The returned array must have the same data type and the same elements as
x.- Return type:
array
- Raises:
ValueError – If
copy=Falseand a copy would be necessary, aValueErrorshould be raised.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.result_type(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the dtype that results from applying type promotion rules (see type-promotion) to the arguments.
- Parameters:
arrays_and_dtypes (Union[array, int, float, complex, bool, dtype]) – an arbitrary number of input arrays, scalars, and/or dtypes.
- Returns:
out – the dtype resulting from an operation involving the input arrays, scalars, and/or dtypes.
- Return type:
Notes
At least one argument must be an array or a dtype.
If provided array and/or dtype arguments having mixed data type kinds (e.g., integer and floating-point), the returned dtype is unspecified and thus implementation-dependent.
If at least one argument is an array, the function must determine the resulting dtype according to the type promotion graph of the array device which is shared among all array arguments. As not all devices can support all data types, full support for type promotion rules (see type-promotion) may not be possible. Accordingly, the returned dtype may differ from that determined from the complete type promotion graph defined in this specification (see type-promotion).
If two or more arguments are arrays belonging to different devices, behavior is unspecified and thus implementation-dependent. Conforming implementations may choose to ignore device attributes, raise an exception, or some other behavior.
Changed in version 2024.12: Added scalar argument support.
Changed in version 2024.12: Required that the application of type promotion rules must account for device context.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.rfft(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the one-dimensional discrete Fourier transform for real-valued input.
Note
Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
irfft(rfft(x)) == x), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms.- Parameters:
x (array) – input array. Must have a real-valued floating-point data type.
n (Optional[int]) –
number of elements over which to compute the transform along the axis (dimension) specified by
axis. LetMbe the size of the input array along the axis specified byaxis. WhennisNone, the function must setnequal toM.If
nis greater thanM, the axis specified byaxismust be zero-padded to sizen.If
nis less thanM, the axis specified byaxismust be trimmed to sizen.If
nequalsM, all elements along the axis specified byaxismust be used when computing the transform.
Default:
None.axis (int) – axis (dimension) of the input array over which to compute the transform. A valid
axismust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If anaxisis specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension). Default:-1.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
Default:
'backward'.
- Returns:
out – an array transformed along the axis (dimension) specified by
axis. The returned array must have a complex floating-point data type whose precision matches the precision ofx(e.g., ifxisfloat64, then the returned array must have acomplex128data type). The returned array must have the same shape asx, except for the axis specified byaxiswhich must have sizen//2 + 1.- Return type:
array
Notes
Added in version 2022.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.rfftfreq(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the discrete Fourier transform sample frequencies (for
rfftandirfft).For a Fourier transform of length
nand length unit ofd, the frequencies are described as:f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd
The Nyquist frequency component is considered to be positive.
- Parameters:
n (int) – window length.
d (float) – sample spacing between individual samples of the Fourier transform input. Default:
1.0.dtype (Optional[dtype]) – output array data type. Must be a real-valued floating-point data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array of shape
(n//2+1,)containing the sample frequencies.- Return type:
array
Notes
Added in version 2022.12.
Changed in version 2023.12: Required the output array have the default real-valued floating-point data type.
Changed in version 2024.12: Added
dtypekeyword argument support.- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.rfftn(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the n-dimensional discrete Fourier transform for real-valued input.
Note
Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e.,
irfftn(rfftn(x)) == x), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes.- Parameters:
x (array) – input array. Must have a real-valued floating-point data type.
s (Optional[Sequence[int]]) –
number of elements over which to compute the transform along axes (dimensions) specified by
axes. Letibe the index of then-th axis specified byaxes(i.e.,i = axes[n]) andM[i]be the size of the input array along axisi. WhensisNone, the function must setsequal to a sequence of integers such thats[i]equalsM[i]for alli.If
s[i]is greater thanM[i], axisimust be zero-padded to sizes[i].If
s[i]is less thanM[i], axisimust be trimmed to sizes[i].If
s[i]equalsM[i]or-1, all elements along axisimust be used when computing the transform.
If
sis notNone,axesmust not beNone. Default:None.axes (Optional[Sequence[int]]) –
axes (dimensions) over which to compute the transform. A valid axis in
axesmust be an integer on the interval[-N, N), whereNis the rank (number of dimensions) ofx. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where-1refers to the last dimension).If
sis provided, the correspondingaxesto be transformed must also be provided. IfaxesisNone, the function must compute the transform over all axes. Default:None.If
axescontains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined.norm (Literal['backward', 'ortho', 'forward']) –
normalization mode. Should be one of the following modes:
'backward': no normalization.'ortho': normalize by1/sqrt(n)(i.e., make the FFT orthonormal).'forward': normalize by1/n.
where
n = prod(s), the logical FFT size.Default:
'backward'.
- Returns:
out – an array transformed along the axes (dimension) specified by
axes. The returned array must have a complex floating-point data type whose precision matches the precision ofx(e.g., ifxisfloat64, then the returned array must have acomplex128data type). The returned array must have the same shape asx, except for the last transformed axis which must have sizes[-1]//2 + 1and the remaining transformed axes which must have sizes[i].- Return type:
array
Notes
Added in version 2022.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.roll(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRolls array elements along a specified axis.
Array elements that roll beyond the last position are re-introduced at the first position.
Array elements that roll beyond the first position are re-introduced at the last position.
- Parameters:
x (array) – input array.
shift (Union[int, Tuple[int, ...]]) – number of places by which the elements are shifted. If
shiftis a tuple, thenaxismust be a tuple of the same size, and each of the given axes must be shifted by the corresponding element inshift. Ifshiftis anintandaxisa tuple, then the sameshiftmust be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension ofaxis. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension ofaxis.axis (Optional[Union[int, Tuple[int, ...]]]) – axis (or axes) along which elements to shift. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. IfaxisisNone, the array must be flattened, shifted, and then restored to its original shape. Default:None.
- Returns:
out – an output array. The returned array must have the same data type as
x. The returned array must have the same elements asx, but which are shifted relative tox.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.round(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRounds each element
x_iof the input arrayxto the nearest integer-valued number.Note
For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number.
Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued
x,real(round(x))must equalround(real(x)))andimag(round(x))must equalround(imag(x))).- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the rounded result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
Note
For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if
real(x_i)isNaN, the rounded real component isNaN).If
x_iis already integer-valued, the result isx_i.
For floating-point operands,
If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iisNaN, the result isNaN.If two integers are equally close to
x_i, the result is the even integer closest tox_i.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.searchsorted(*args, **kwargs)[source]¶
Bases:
Protocol,GenericFinds the indices into
x1such that, if the corresponding elements inx2were inserted before the indices, the order ofx1, when sorted in ascending order, would be preserved.- Parameters:
x1 (array) – input array. Must be a one-dimensional array. Should have a real-valued data type. If
sorterisNone, must be sorted in ascending order; otherwise,sortermust be an array of indices that sortx1in ascending order.x2 (Union[array, int, float]) – array containing search values. Should have a real-valued data type.
side (Literal['left', 'right']) –
argument controlling which index is returned if a value lands exactly on an edge.
Let
vbe an element ofx2given byv = x2[j], wherejrefers to a valid index (see indexing).If
vis less than all elements inx1, thenout[j]must be0.If
vis greater than all elements inx1, thenout[j]must beM, whereMis the number of elements inx1.Otherwise, each returned index
i = out[j]must satisfy an index condition:If
side == 'left', thenx1[i-1] < v <= x1[i].If
side == 'right', thenx1[i-1] <= v < x1[i].
Default:
'left'.sorter (Optional[array]) – array of indices that sort
x1in ascending order. The array must have the same shape asx1and have an integer data type. Default:None.
- Returns:
out – an array of indices with the same shape as
x2. The returned array must have the default array index data type.- Return type:
array
Notes
If
x2is a scalar value,x2should be treated as equivalent to a zero-dimensional array having a data type determined according to mixing-scalars-and-arrays.For real-valued floating-point arrays, the sort order of NaNs and signed zeros is unspecified and thus implementation-dependent. Accordingly, when a real-valued floating-point array contains NaNs and signed zeros, what constitutes ascending order may vary among specification-conforming array libraries.
While behavior for arrays containing NaNs and signed zeros is implementation-dependent, specification-conforming libraries should, however, ensure consistency with
sortandargsort(i.e., if a value inx2is inserted intox1according to the corresponding index in the output array andsortis invoked on the resultant array, the sorted result should be an array in the same order).
Added in version 2023.12.
Changed in version 2024.12: Fixed incorrect boundary conditions.
Changed in version 2025.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.sign(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns an indication of the sign of a number for each element
x_iof the input arrayx.The sign function (also known as the signum function) of a number \(x_i\) is defined as
\[\begin{split}\operatorname{sign}(x_i) = \begin{cases} 0 & \textrm{if } x_i = 0 \\ \frac{x_i}{|x_i|} & \textrm{otherwise} \end{cases}\end{split}\]where \(|x_i|\) is the absolute value of \(x_i\).
- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
For real-valued operands,
If
x_iis less than0, the result is-1.If
x_iis either-0or+0, the result is0.If
x_iis greater than0, the result is+1.If
x_iisNaN, the result isNaN.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either-0or+0andbis either-0or+0, the result is0 + 0j.If
aisNaNorbisNaN, the result isNaN + NaN j.In the remaining cases, special cases must be handled according to the rules of complex number division (see
divide()).
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.signbit(*args, **kwargs)[source]¶
Bases:
Protocol,GenericDetermines whether the sign bit is set for each element
x_iof the input arrayx.The sign bit of a real-valued floating-point number
x_iis set wheneverx_iis either-0, less than zero, or a signedNaN(i.e., aNaNvalue whose sign bit is1).- Parameters:
x (array) – input array. Should have a real-valued floating-point data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a data type ofbool.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iis+0, the result isFalse.If
x_iis-0, the result isTrue.If
x_iis+infinity, the result isFalse.If
x_iis-infinity, the result isTrue.If
x_iis a positive (i.e., greater than0) finite number, the result isFalse.If
x_iis a negative (i.e., less than0) finite number, the result isTrue.If
x_iisNaNand the sign bit ofx_iis0, the result isFalse.If
x_iisNaNand the sign bit ofx_iis1, the result isTrue.
Added in version 2023.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.sin(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the sine for each element
x_iof the input arrayx.Each element
x_iis assumed to be expressed in radians.Note
The sine is an entire function on the complex plane and has no branch cuts.
Note
For complex arguments, the mathematical definition of sine is
\[\begin{split}\begin{align} \operatorname{sin}(x) &= \frac{e^{jx} - e^{-jx}}{2j} \\ &= \frac{\operatorname{sinh}(jx)}{j} \\ &= \frac{\operatorname{sinh}(jx)}{j} \cdot \frac{j}{j} \\ &= -j \cdot \operatorname{sinh}(jx) \end{align}\end{split}\]where \(\operatorname{sinh}\) is the hyperbolic sine.
- Parameters:
x (array) – input array whose elements are each expressed in radians. Should have a floating-point data type.
- Returns:
out – an array containing the sine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis either+infinityor-infinity, the result isNaN.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
-1j * sinh(x*1j).Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.sinh(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the hyperbolic sine for each element
x_iof the input arrayx.The mathematical definition of the hyperbolic sine is
\[\operatorname{sinh}(x) = \frac{e^x - e^{-x}}{2}\]Note
The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period \(2\pi j\), with respect to the imaginary component.
- Parameters:
x (array) – input array whose elements each represent a hyperbolic angle. Should have a floating-point data type.
- Returns:
out – an array containing the hyperbolic sine of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
Note
For all operands,
sinh(x)must equal-sinh(-x).For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andNote
For complex floating-point operands,
sinh(conj(x))must equalconj(sinh(x)).If
ais+0andbis+0, the result is+0 + 0j.If
ais+0andbis+infinity, the result is0 + NaN j(sign of the real component is unspecified).If
ais+0andbisNaN, the result is0 + NaN j(sign of the real component is unspecified).If
ais a positive (i.e., greater than0) finite number andbis+infinity, the result isNaN + NaN j.If
ais a positive (i.e., greater than0) finite number andbisNaN, the result isNaN + NaN j.If
ais+infinityandbis+0, the result is+infinity + 0j.If
ais+infinityandbis a positive finite number, the result is+infinity * cis(b).If
ais+infinityandbis+infinity, the result isinfinity + NaN j(sign of the real component is unspecified).If
ais+infinityandbisNaN, the result isinfinity + NaN j(sign of the real component is unspecified).If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis a nonzero finite number, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
where
cis(v)iscos(v) + sin(v)*1j.Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.slogdet(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the sign and the natural logarithm of the absolute value of the determinant of a square matrix (or a stack of square matrices)
x.Note
The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling
detmay overflow or underflow.The sign of the determinant is given by
\[\begin{split}\operatorname{sign}(\det x) = \begin{cases} 0 & \textrm{if } \det x = 0 \\ \frac{\det x}{|\det x|} & \textrm{otherwise} \end{cases}\end{split}\]where \(|\det x|\) is the absolute value of the determinant of
x.When
xis a stack of matrices, the function must compute the sign and natural logarithm of the absolute value of the determinant for each matrix in the stack.Special Cases
For real-valued floating-point operands,
If the determinant is zero, the
signshould be0andlogabsdetshould be-infinity.
For complex floating-point operands,
If the determinant is
0 + 0j, thesignshould be0 + 0jandlogabsdetshould be-infinity + 0j.
Note
Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from
-infinity(or-infinity + 0j). In all cases, the determinant should be equal tosign * exp(logabsdet)(although, again, the result may be subject to numerical precision errors).- Parameters:
x (array) – input array having shape
(..., M, M)and whose innermost two dimensions form square matrices. Should have a floating-point data type.- Returns:
out – a namedtuple (
sign,logabsdet) whosefirst element must have the field name
signand must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type asx.second element must have the field name
logabsdetand must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. Ifxis real-valued, the returned array must have a real-valued floating-point data type determined by type-promotion. Ifxis complex, the returned array must have a real-valued floating-point data type having the same precision asx(e.g., ifxiscomplex64,logabsdetmust have afloat32data type).
Each returned array must have shape
shape(x)[:-2].- Return type:
Tuple[array, array]
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.solve(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the solution of a square system of linear equations with a unique solution.
Let
x1equal \(A\) andx2equal \(B\). If the promoted data type ofx1andx2is real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, if the promoted data type ofx1andx2is complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).This function computes the solution \(X \in\ \mathbb{K}^{m \times k}\) of the linear system associated to \(A \in\ \mathbb{K}^{m \times m}\) and \(B \in\ \mathbb{K}^{m \times k}\) and is defined as
\[AX = B\]This system of linear equations has a unique solution if and only if \(A\) is invertible.
Note
Whether an array library explicitly checks whether
x1is invertible is implementation-defined.When
x1and/orx2is a stack of matrices, the function must compute a solution for each matrix in the stack.- Parameters:
x1 (array) – coefficient array
Ahaving shape(..., M, M)and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type.x2 (array) – ordinate (or “dependent variable”) array
B. Ifx2has shape(M,),x2is equivalent to an array having shape(..., M, 1). Ifx2has shape(..., M, K), each columnkdefines a set of ordinate values for which to compute a solution, andshape(x2)[:-2]must be compatible withshape(x1)[:-2](see broadcasting). Should have a floating-point data type.
- Returns:
out – an array containing the solution to the system
AX = Bfor each square matrix. Ifx2has shape(M,), the returned array must have shape equal toshape(x1)[:-2] + shape(x2)[-1:]. Otherwise, ifx2has shape(..., M, K)`, the returned array must have shape equal to(..., M, K), where...refers to the result of broadcastingshape(x1)[:-2]andshape(x2)[:-2]. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Clarified broadcasting semantics and the shape of the output array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.sort(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a sorted copy of an input array
x.- Parameters:
x (array) – input array. Should have a real-valued data type.
axis (int) – axis along which to sort. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:-1.descending (bool) – sort order. If
True, the array must be sorted in descending order (by value). IfFalse, the array must be sorted in ascending order (by value). Default:False.stable (bool) – sort stability. If
True, the returned array must maintain the relative order ofxvalues which compare as equal. IfFalse, the returned array may maintain the relative order ofxvalues which compare as equal (i.e., the relative order ofxvalues which compare as equal is implementation-dependent). Default:True.
- Returns:
out – a sorted array. The returned array must have the same data type and shape as
x.- Return type:
array
Notes
For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see complex-number-ordering).
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.sqrt(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the principal square root for each element
x_iof the input arrayx.Note
After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754).
Note
For complex floating-point operands,
sqrt(conj(x))must equalconj(sqrt(x)).Note
By convention, the branch cut of the square root is the negative real axis \((-\infty, 0)\).
The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component.
Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by \([0, +\infty)\) along the real axis and \((-\infty, +\infty)\) along the imaginary axis).
Note: branch cuts follow C99 and have provisional status (see branch-cuts).
- Parameters:
x (array) – input array. Should have a floating-point data type.
- Returns:
out – an array containing the square root of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis less than0, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+infinity.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andIf
ais either+0or-0andbis+0, the result is+0 + 0j.If
ais any value (includingNaN) andbis+infinity, the result is+infinity + infinity j.If
ais a finite number andbisNaN, the result isNaN + NaN j.If
a-infinityandbis a positive (i.e., greater than0) finite number, the result is+0 + infinity j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is+infinity + 0 j.If
ais-infinityandbisNaN, the result isNaN + infinity j(sign of the imaginary component is unspecified).If
ais+infinityandbisNaN, the result is+infinity + NaN j.If
aisNaNandbis any value, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.square(*args, **kwargs)[source]¶
Bases:
Protocol,GenericSquares each element
x_iof the input arrayx.The square of a number
x_iis defined as\[x_i^2 = x_i \cdot x_i\]- Parameters:
x (array) – input array. Should have a numeric data type.
- Returns:
out – an array containing the evaluated result for each element in
x. The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
Special cases
For floating-point operands, special cases must be handled as if the operation is implemented as
x * x(seemultiply()).Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.squeeze(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRemoves singleton axes from
x.- Parameters:
x (array) – input array.
axis (Union[int, Tuple[int, ...]]) – axis (or axes) to squeeze. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.
- Returns:
out – an output array. The returned array must have the same data type and the same elements as
x.- Return type:
array
- Raises:
ValueError – If a specified axis has a size greater than one (i.e., it is not a singleton axis), a
ValueErrorshould be raised.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.stack(*args, **kwargs)[source]¶
Bases:
Protocol,GenericJoins a sequence of arrays along a new axis.
- Parameters:
arrays (Union[Tuple[array, ...], List[array]]) – input arrays to join. Each array must have the same shape.
axis (int) – axis along which to join the arrays. Providing an
axisspecifies the index of the new axis in the shape of the result. For example, ifaxisis0, the new axis must be the first dimension and the output array must have shape(N, A, B, C); ifaxisis1, the new axis will be the second dimension and the output array will have shape(A, N, B, C); and, ifaxisis-1, the new axis will be the last dimension and the output array will have shape(A, B, C, N). A valid axis must be an integer on the interval[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:0.
- Returns:
out – an output array. The returned array must have
N+1axes, whereNis the number of axes inx. If the input arrays have different data types, normal type-promotion must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays.- Return type:
array
Notes
This specification leaves type promotion between data type families (i.e.,
intxxandfloatxx) unspecified and thus implementation-defined.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.std(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the standard deviation of the input array
x.- Parameters:
x (array) – input array. Should have a real-valued floating-point data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to compute standard deviations. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.correction (Union[int, float]) – degrees of freedom adjustment. Setting this parameter to a value other than
0has the effect of adjusting the divisor during the calculation of the standard deviation according toM-cwhereMcorresponds to the total number of elements over which the standard deviation is computed andccorresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to0is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to1is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel’s correction). Default:0.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the standard deviation is computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as
x.- Return type:
array
Notes
While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array
xhas an integer data type, the returned array must have the default real-valued floating-point data type.
Special Cases
Let
Mequal the number of elements over which to compute the standard deviation.If
M - correctionis less than or equal to0, the standard deviation must beNaN.If
x_iisNaN, the standard deviation must beNaN(i.e.,NaNvalues propagate).
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.subtract(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the difference for each element
x1_iof the input arrayx1with the respective elementx2_iof the input arrayx2.- Parameters:
x1 (Union[array, int, float, complex]) – first input array. Should have a numeric data type.
x2 (Union[array, int, float, complex]) – second input array. Must be compatible with
x1(see broadcasting). Should have a numeric data type.
- Returns:
out – an array containing the element-wise differences. The returned array must have a data type determined by type-promotion.
- Return type:
array
Notes
At least one of
x1orx2must be an array.The result of
x1_i - x2_imust be the same asx1_i + (-x2_i)and must be governed by the same floating-point rules as addition (seeadd()).
Changed in version 2022.12: Added complex data type support.
Changed in version 2024.12: Added scalar argument support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.sum(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the sum of the input array
x.- Parameters:
x (array) – input array. Should have a numeric data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the sum (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the sum is computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the
dtypeparameter above.- Return type:
array
Notes
Special Cases
Let
Mequal the number of elements over which to compute the sum.If
Mis0, the sum must be0(i.e., the empty sum).
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
add().Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.svd(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a singular value decomposition (SVD) of a matrix (or a stack of matrices)
x.If
xis real-valued, let \(\mathbb{K}\) be the set of real numbers \(\mathbb{R}\), and, ifxis complex-valued, let \(\mathbb{K}\) be the set of complex numbers \(\mathbb{C}\).The full singular value decomposition of an \(m \times n\) matrix \(x \in\ \mathbb{K}^{m \times n}\) is a factorization of the form
\[x = U \Sigma V^H\]where \(U \in\ \mathbb{K}^{m \times m}\), \(\Sigma \in\ \mathbb{K}^{m \times\ n}\), \(\operatorname{diag}(\Sigma) \in\ \mathbb{R}^{k}\) with \(k = \operatorname{min}(m, n)\), \(V^H \in\ \mathbb{K}^{n \times n}\), and where \(V^H\) is the conjugate transpose when \(V\) is complex and the transpose when \(V\) is real-valued. When
xis real-valued, \(U\), \(V\) (and thus \(V^H\)) are orthogonal, and, whenxis complex, \(U\), \(V\) (and thus \(V^H\)) are unitary.When \(m \gt n\) (tall matrix), we can drop the last \(m - n\) columns of \(U\) to form the reduced SVD
\[x = U \Sigma V^H\]where \(U \in\ \mathbb{K}^{m \times k}\), \(\Sigma \in\ \mathbb{K}^{k \times\ k}\), \(\operatorname{diag}(\Sigma) \in\ \mathbb{R}^{k}\), and \(V^H \in\ \mathbb{K}^{k \times n}\). In this case, \(U\) and \(V\) have orthonormal columns.
Similarly, when \(n \gt m\) (wide matrix), we can drop the last \(n - m\) columns of \(V\) to also form a reduced SVD.
This function returns the decomposition \(U\), \(S\), and \(V^H\), where \(S = \operatorname{diag}(\Sigma)\).
When
xis a stack of matrices, the function must compute the singular value decomposition for each matrix in the stack.Warning
The returned arrays \(U\) and \(V\) are neither unique nor continuous with respect to
x. Because \(U\) and \(V\) are not unique, different hardware and software may compute different singular vectors.Non-uniqueness stems from the fact that multiplying any pair of singular vectors \(u_k\), \(v_k\) by \(-1\) when
xis real-valued and by \(e^{\phi j}\) (\(\phi \in \mathbb{R}\)) whenxis complex produces another two valid singular vectors of the matrix.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type.full_matrices (bool) – If
True, compute full-sizedUandVh, such thatUhas shape(..., M, M)andVhhas shape(..., N, N). IfFalse, compute on the leadingKsingular vectors, such thatUhas shape(..., M, K)andVhhas shape(..., K, N)and whereK = min(M, N). Default:True.
- Returns:
out – a namedtuple
(U, S, Vh)whosefirst element must have the field name
Uand must be an array whose shape depends on the value offull_matricesand contain matrices with orthonormal columns (i.e., the columns are left singular vectors). Iffull_matricesisTrue, the array must have shape(..., M, M). Iffull_matricesisFalse, the array must have shape(..., M, K), whereK = min(M, N). The firstx.ndim-2dimensions must have the same shape as those of the inputx. Must have the same data type asx.second element must have the field name
Sand must be an array with shape(..., K)that contains the vector(s) of singular values of lengthK, whereK = min(M, N). For each vector, the singular values must be sorted in descending order by magnitude, such thats[..., 0]is the largest value,s[..., 1]is the second largest value, et cetera. The firstx.ndim-2dimensions must have the same shape as those of the inputx. Must have a real-valued floating-point data type having the same precision asx(e.g., ifxiscomplex64,Smust have afloat32data type).third element must have the field name
Vhand must be an array whose shape depends on the value offull_matricesand contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). Iffull_matricesisTrue, the array must have shape(..., N, N). Iffull_matricesisFalse, the array must have shape(..., K, N)whereK = min(M, N). The firstx.ndim-2dimensions must have the same shape as those of the inputx. Must have the same data type asx.
- Return type:
Tuple[array, array, array]
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.svdvals(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the singular values of a matrix (or a stack of matrices)
x.When
xis a stack of matrices, the function must compute the singular values for each matrix in the stack.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type.- Returns:
out – an array with shape
(..., K)that contains the vector(s) of singular values of lengthK, whereK = min(M, N). For each vector, the singular values must be sorted in descending order by magnitude, such thats[..., 0]is the largest value,s[..., 1]is the second largest value, et cetera. The firstx.ndim-2dimensions must have the same shape as those of the inputx. The returned array must have a real-valued floating-point data type having the same precision asx(e.g., ifxiscomplex64, the returned array must have afloat32data type).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.take(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns elements of an array along an axis.
- Parameters:
x (array) – input array. Should have one or more axes.
indices (array) – array indices. The array must be one-dimensional and have an integer data type. If an index is negative, the function must determine the element to select along a specified axis by counting from the last element (where
-1refers to the last element).axis (Optional[int]) –
axis over which to select values. If
axisis negative, the function must determine the axis along which to select values by counting from the last axis (where-1refers to the last axis).If
xis a one-dimensional array, providing anaxismust be optional; however, ifxhas more than one axis, providing anaxismust be required.
- Returns:
out – an array having the same data type as
x. The output array must have the same number of axes asxand must have the same shape asx, except for the axis specified byaxiswhose size must equal the number of elements inindices.- Return type:
array
Notes
This specification does not require bounds checking. The behavior for out-of-bounds indices is unspecified and thus implementation-defined.
When
xis a zero-dimensional array, behavior is unspecified and thus implementation-defined.
Added in version 2022.12.
Changed in version 2023.12: Out-of-bounds behavior is explicitly left unspecified.
Changed in version 2024.12: Behavior when provided a zero-dimensional input array is explicitly left unspecified.
Changed in version 2024.12: Clarified support for negative indices.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.take_along_axis(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns elements from an array at the one-dimensional indices specified by
indicesalong a providedaxis.- Parameters:
x (array) – input array. Must be compatible with
indices, except for the axis specified byaxis(see broadcasting).indices (array) – array indices. Must have the same number of axes as
xand must be compatible withx, except for the axis specified byaxis(see broadcasting). If an index is negative, the function must determine the element to select along a specified axis by counting from the last element (where-1refers to the last element).axis (int) – axis along which to select values. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:-1.
- Returns:
out – an array containing elements from
x. The returned array must have the same data type asx. The returned array must have the same number of axes asxand must have a shape determined according to broadcasting, except for the axis specified byaxiswhose size must equal the size of the corresponding axis inindices.- Return type:
array
Notes
This specification does not require bounds checking. The behavior for out-of-bounds indices is unspecified and thus implementation-defined.
Added in version 2024.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.tan(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the tangent for each element
x_iof the input arrayx.Each element
x_iis assumed to be expressed in radians.Note
Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period \(\pi j\), with respect to the real component and has first order poles along the real line at coordinates \((\pi (\frac{1}{2} + n), 0)\). However, IEEE 754 binary floating-point representation cannot represent the value \(\pi / 2\) exactly, and, thus, no argument value is possible for which a pole error occurs.
Note
For complex arguments, the mathematical definition of tangent is
\[\begin{split}\begin{align} \operatorname{tan}(x) &= \frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\ &= (-1) \frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\ &= -j \cdot \operatorname{tanh}(jx) \end{align}\end{split}\]where \(\operatorname{tanh}\) is the hyperbolic tangent.
- Parameters:
x (array) – input array whose elements are expressed in radians. Should have a floating-point data type.
- Returns:
out – an array containing the tangent of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis either+infinityor-infinity, the result isNaN.
For complex floating-point operands, special cases must be handled as if the operation is implemented as
-1j * tanh(x*1j).Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.tanh(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates an implementation-dependent approximation to the hyperbolic tangent for each element
x_iof the input arrayx.The mathematical definition of the hyperbolic tangent is
\[\begin{split}\begin{align} \operatorname{tanh}(x) &= \frac{\operatorname{sinh}(x)}{\operatorname{cosh}(x)} \\ &= \frac{e^x - e^{-x}}{e^x + e^{-x}} \end{align}\end{split}\]where \(\operatorname{sinh}(x)\) is the hyperbolic sine and \(\operatorname{cosh}(x)\) is the hyperbolic cosine.
Note
The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period \(\pi j\), with respect to the imaginary component and has first order poles along the imaginary line at coordinates \((0, \pi (\frac{1}{2} + n))\). However, IEEE 754 binary floating-point representation cannot represent \(\pi / 2\) exactly, and, thus, no argument value is possible such that a pole error occurs.
- Parameters:
x (array) – input array whose elements each represent a hyperbolic angle. Should have a floating-point data type.
- Returns:
out – an array containing the hyperbolic tangent of each element in
x. The returned array must have a floating-point data type determined by type-promotion.- Return type:
array
Notes
Special cases
Note
For all operands,
tanh(-x)must equal-tanh(x).For real-valued floating-point operands,
If
x_iisNaN, the result isNaN.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iis+infinity, the result is+1.If
x_iis-infinity, the result is-1.
For complex floating-point operands, let
a = real(x_i),b = imag(x_i), andNote
For complex floating-point operands,
tanh(conj(x))must equalconj(tanh(x)).If
ais+0andbis+0, the result is+0 + 0j.If
ais a nonzero finite number andbis+infinity, the result isNaN + NaN j.If
ais+0andbis+infinity, the result is+0 + NaN j.If
ais a nonzero finite number andbisNaN, the result isNaN + NaN j.If
ais+0andbisNaN, the result is+0 + NaN j.If
ais+infinityandbis a positive (i.e., greater than0) finite number, the result is1 + 0j.If
ais+infinityandbis+infinity, the result is1 + 0j(sign of the imaginary component is unspecified).If
ais+infinityandbisNaN, the result is1 + 0j(sign of the imaginary component is unspecified).If
aisNaNandbis+0, the result isNaN + 0j.If
aisNaNandbis a nonzero number, the result isNaN + NaN j.If
aisNaNandbisNaN, the result isNaN + NaN j.
Warning
For historical reasons stemming from the C standard, array libraries may not return the expected result when
ais+0andbis either+infinityorNaN. The result should be+0 + NaN jin both cases; however, for libraries compiled against older C versions, the result may beNaN + NaN j.Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases.
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.tensordot(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a tensor contraction of
x1andx2over specific axes.- Parameters:
x1 (array) – first input array. Should have a numeric data type.
x2 (array) – second input array. Should have a numeric data type. Corresponding contracted axes of
x1andx2must be equal.axes (Union[int, Tuple[Sequence[int], Sequence[int]]]) –
number of axes to contract or explicit sequences of axis indices for
x1andx2, respectively.If
axesis anintequal toN, then contraction must be performed over the lastNaxes ofx1and the firstNaxes ofx2in order. The size of each corresponding axis must match. An integeraxesvalue must be nonnegative.If
Nequals0, the result must be the tensor (outer) product.If
Nequals1, the result must be the tensor dot product.If
Nequals2, the result must be the tensor double contraction (default).
If
axesis a tuple of two sequences(x1_axes, x2_axes), the first sequence must apply tox1and the second sequence must apply tox2. Both sequences must have the same length. Each axisx1_axes[i]forx1must have the same size as the respective axisx2_axes[i]forx2. Each index referred to in a sequence must be unique. A valid axis must be an integer on the interval[-S, S), whereSis the number of axes in respective array. Hence, ifx1hasNaxes, a validx1axes must be an integer on the interval[-N, N). Ifx2hasMaxes, a validx2axes must be an integer on the interval[-M, M). If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception.
- Returns:
out – an array containing the tensor contraction. The returned array must have a shape which consists of the non-contracted axes of the first array
x1, followed by the non-contracted axes of the second arrayx2. The returned array must have a data type determined by type-promotion.- Return type:
array
Notes
The
tensordotfunction corresponds to the generalized matrix product.Contracted axes must not be broadcasted.
If either
x1orx2has a complex floating-point data type, the function must not complex-conjugate or transpose either argument. If conjugation and/or transposition is desired, a user can explicitly perform these operations prior to computing the generalized matrix product.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Allow negative axes.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.tile(*args, **kwargs)[source]¶
Bases:
Protocol,GenericConstructs an array by tiling an input array.
- Parameters:
x (array) – input array.
repetitions (Tuple[int, ...]) –
number of repetitions along each axis.
Let
N = len(x.shape)andM = len(repetitions).If
N > M, the function must prepend ones until all axes are specified (e.g., ifxhas shape(8,6,4,2)andrepetitionsis the tuple(3,3), thenrepetitionsmust be treated as(1,1,3,3)).If
N < M, the function must prepend singleton axes toxuntilxhas as many axes asrepetitionsspecifies (e.g., ifxhas shape(4,2)andrepetitionsis the tuple(3,3,3,3), thenxmust be treated as if it has shape(1,1,4,2)).
- Returns:
out – a tiled output array. The returned array must have the same data type as
xand must have a number of axes equal tomax(N, M). IfSis the shape of the tiled array after prepending singleton dimensions (if necessary) andris the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis must satisfyS[i]*r[i], whereirefers to theith axis.- Return type:
array
Notes
Added in version 2023.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.trace(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the sum along the specified diagonals of a matrix (or a stack of matrices)
x.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices. Should have a numeric data type.offset (int) –
offset specifying the off-diagonal relative to the main diagonal.
offset = 0: the main diagonal.offset > 0: off-diagonal above the main diagonal.offset < 0: off-diagonal below the main diagonal.
Default:
0.dtype (Optional[dtype]) –
data type of the returned array. If
None, the returned array must have the same data type asx, unlessxhas an integer data type supporting a smaller range of values than the default integer data type (e.g.,xhas anint16oruint32data type and the default integer data type isint64). In those latter cases:if
xhas a signed integer data type (e.g.,int16), the returned array must have the default integer data type.if
xhas an unsigned integer data type (e.g.,uint16), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type isint32, the returned array must have auint32data type).
If the data type (either specified or resolved) differs from the data type of
x, the input array should be cast to the specified data type before computing the sum (rationale: thedtypekeyword argument is intended to help prevent overflows). Default:None.
- Returns:
out – an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if
xhas rankkand shape(I, J, K, ..., L, M, N), then an output array has rankk-2and shape(I, J, K, ..., L)whereout[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :])
The returned array must have a data type as described by the
dtypeparameter above.- Return type:
array
Notes
Special Cases
Let
Nequal the number of elements over which to compute the sum.If
Nis0, the sum is0(i.e., the empty sum).
For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of
add().Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.tril(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the lower triangular part of a matrix (or a stack of matrices)
x.Note
The lower triangular part of the matrix is defined as the elements on and below the specified diagonal
k.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices.k (int) –
diagonal above which to zero elements. If
k = 0, the diagonal is the main diagonal. Ifk < 0, the diagonal is below the main diagonal. Ifk > 0, the diagonal is above the main diagonal. Default:0.Note
The main diagonal is defined as the set of indices
{(i, i)}forion the interval[0, min(M, N) - 1].
- Returns:
out – an array containing the lower triangular part(s). The returned array must have the same shape and data type as
x. All elements above the specified diagonalkmust be zeroed. The returned array should be allocated on the same device asx.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.triu(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the upper triangular part of a matrix (or a stack of matrices)
x.Note
The upper triangular part of the matrix is defined as the elements on and above the specified diagonal
k.- Parameters:
x (array) – input array having shape
(..., M, N)and whose innermost two dimensions formMxNmatrices.k (int) –
diagonal below which to zero elements. If
k = 0, the diagonal is the main diagonal. Ifk < 0, the diagonal is below the main diagonal. Ifk > 0, the diagonal is above the main diagonal. Default:0.Note
The main diagonal is defined as the set of indices
{(i, i)}forion the interval[0, min(M, N) - 1].
- Returns:
out – an array containing the upper triangular part(s). The returned array must have the same shape and data type as
x. All elements below the specified diagonalkmust be zeroed. The returned array should be allocated on the same device asx.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.trunc(*args, **kwargs)[source]¶
Bases:
Protocol,GenericRounds each element
x_iof the input arrayxto the nearest integer-valued number that is closer to zero thanx_i.- Parameters:
x (array) – input array. Should have a real-valued data type.
- Returns:
out – an array containing the rounded result for each element in
x. The returned array must have the same data type asx.- Return type:
array
Notes
Special cases
If
x_iis already integer-valued, the result isx_i.
For floating-point operands,
If
x_iis+infinity, the result is+infinity.If
x_iis-infinity, the result is-infinity.If
x_iis+0, the result is+0.If
x_iis-0, the result is-0.If
x_iisNaN, the result isNaN.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.unique_all(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the unique elements of an input array
x, the first occurring indices for each unique element inx, the indices from the set of unique elements that reconstructx, and the corresponding counts for each unique element inx.Data-dependent output shape
The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, et cetera) can find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. If
xhas more than one dimension, the function must flattenxand return the unique elements of the flattened array.- Returns:
out – a namedtuple
(values, indices, inverse_indices, counts)whosefirst element must have the field name
valuesand must be a one-dimensional array containing the unique elements ofx. The array must have the same data type asx.second element must have the field name
indicesand must be an array containing the indices (first occurrences) of a flattenedxthat result invalues. The array must have the same shape asvaluesand must have the default array index data type.third element must have the field name
inverse_indicesand must be an array containing the indices ofvaluesthat reconstructx. The array must have the same shape asxand must have the default array index data type.fourth element must have the field name
countsand must be an array containing the number of times each unique element occurs inx. The order of the returned counts must match the order ofvalues, such that a specific element incountscorresponds to the respective unique element invalues. The returned array must have same shape asvaluesand must have the default array index data type.
- Return type:
Tuple[array, array, array, array]
Notes
The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order may vary between implementations.
Uniqueness should be determined based on value equality (see
equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.As
nanvalues compare asFalse,nanvalues should be considered distinct.As complex floating-point values having at least one
nancomponent compare asFalse, complex floating-point values havingnancomponents should be considered distinct.As
-0and+0compare asTrue, signed zeros should not be considered distinct, and the corresponding unique element may be implementation-defined (e.g., an implementation may choose to return-0if-0occurs before+0).
As signed zeros are not distinct, using
inverse_indicesto reconstruct the input array is not guaranteed to return an array having the exact same values.Each
nanvalue and each complex floating-point value having anancomponent should have a count of one, while the counts for signed zeros should be aggregated as a single count.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Clarified flattening behavior and required the order of
countsmatch the order ofvalues.- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.unique_counts(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the unique elements of an input array
xand the corresponding counts for each unique element inx.Data-dependent output shape
The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. If
xhas more than one dimension, the function must flattenxand return the unique elements of the flattened array.- Returns:
out – a namedtuple (values, counts) whose
first element must have the field name
valuesand must be a one-dimensional array containing the unique elements ofx. The array must have the same data type asx.second element must have the field name counts and must be an array containing the number of times each unique element occurs in
x. The order of the returned counts must match the order ofvalues, such that a specific element incountscorresponds to the respective unique element invalues. The returned array must have same shape asvaluesand must have the default array index data type.
- Return type:
Tuple[array, array]
Notes
The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order may vary between implementations.
Uniqueness should be determined based on value equality (see
equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.As
nanvalues compare asFalse,nanvalues should be considered distinct.As complex floating-point values having at least one
nancomponent compare asFalse, complex floating-point values havingnancomponents should be considered distinct.As
-0and+0compare asTrue, signed zeros should not be considered distinct, and the corresponding unique element may be implementation-defined (e.g., an implementation may choose to return-0if-0occurs before+0).
Each
nanvalue and each complex floating-point value having anancomponent should have a count of one, while the counts for signed zeros should be aggregated as a single count.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Clarified flattening behavior and required the order of
countsmatch the order ofvalues.- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.unique_inverse(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the unique elements of an input array
xand the indices from the set of unique elements that reconstructx.Data-dependent output shape
The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. If
xhas more than one dimension, the function must flattenxand return the unique elements of the flattened array.- Returns:
out – a namedtuple
(values, inverse_indices)whosefirst element must have the field name
valuesand must be a one-dimensional array containing the unique elements ofx. The array must have the same data type asx.second element must have the field name
inverse_indicesand must be an array containing the indices ofvaluesthat reconstructx. The array must have the same shape asxand have the default array index data type.
- Return type:
Tuple[array, array]
Notes
The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order may vary between implementations.
Uniqueness should be determined based on value equality (see
equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.As
nanvalues compare asFalse,nanvalues should be considered distinct.As complex floating-point values having at least one
nancomponent compare asFalse, complex floating-point values havingnancomponents should be considered distinct.As
-0and+0compare asTrue, signed zeros should not be considered distinct, and the corresponding unique element may be implementation-defined (e.g., an implementation may choose to return-0if-0occurs before+0).
As signed zeros are not distinct, using
inverse_indicesto reconstruct the input array is not guaranteed to return an array having the exact same values.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Clarified flattening behavior.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.unique_values(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns the unique elements of an input array
x.Data-dependent output shape
The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See data-dependent-output-shapes section for more details.
- Parameters:
x (array) – input array. If
xhas more than one dimension, the function must flattenxand return the unique elements of the flattened array.- Returns:
out – a one-dimensional array containing the set of unique elements in
x. The returned array must have the same data type asx.- Return type:
array
Notes
The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order may vary between implementations.
Uniqueness should be determined based on value equality (see
equal()). For input arrays having floating-point data types, value-based equality implies the following behavior.As
nanvalues compare asFalse,nanvalues should be considered distinct.As complex floating-point values having at least one
nancomponent compare asFalse, complex floating-point values havingnancomponents should be considered distinct.As
-0and+0compare asTrue, signed zeros should not be considered distinct, and the corresponding unique element may be implementation-defined (e.g., an implementation may choose to return-0if-0occurs before+0).
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Required that the output array must be one-dimensional.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.unstack(*args, **kwargs)[source]¶
Bases:
Protocol,GenericSplits an array into a sequence of arrays along the given axis.
- Parameters:
x (array) – input array.
axis (int) – axis along which to split an array. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:0.
- Returns:
out – tuple of slices along the given dimension. Each returned array must have the same shape.
- Return type:
Tuple[array, …]
Notes
Added in version 2023.12.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.var(*args, **kwargs)[source]¶
Bases:
Protocol,GenericCalculates the variance of the input array
x.- Parameters:
x (array) – input array. Should have a real-valued floating-point data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:None.correction (Union[int, float]) – degrees of freedom adjustment. Setting this parameter to a value other than
0has the effect of adjusting the divisor during the calculation of the variance according toM-cwhereMcorresponds to the total number of elements over which the variance is computed andccorresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to0is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to1is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel’s correction). Default:0.keepdims (bool) – if
True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the reduced axes (dimensions) must not be included in the result. Default:False.
- Returns:
out – if the variance is computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as
x.- Return type:
array
Notes
While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array
xhas an integer data type, the returned array must have the default real-valued floating-point data type.
Special Cases
Let
Mequal the number of elements over which to compute the variance.If
M - correctionis less than or equal to0, the variance must beNaN.If
x_iisNaN, the variance must beNaN(i.e.,NaNvalues propagate).
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.vecdot(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the (vector) dot product of two arrays.
Let \(\mathbf{a}\) be a vector in
x1and \(\mathbf{b}\) be a corresponding vector inx2. The dot product is defined as\[\mathbf{a} \cdot \mathbf{b} = \sum_{i=0}^{n-1} \overline{a_i}b_i\]over the axis specified by
axisand where \(n\) is the axis size and \(\overline{a_i}\) denotes the complex conjugate if \(a_i\) is complex and the identity if \(a_i\) is real-valued.- Parameters:
x1 (array) – first input array. Should have a floating-point data type.
x2 (array) – second input array. Must be compatible with
x1for all non-contracted axes (see broadcasting). The size of the axis over which to compute the dot product must be the same size as the respective axis inx1. Should have a floating-point data type.axis (int) – axis of
x1andx2containing the vectors for which to compute the dot product. Should be an integer on the interval[-N, -1], whereNismin(x1.ndim, x2.ndim). The function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). By default, the function must compute the dot product over the last axis. Default:-1.
- Returns:
out – if
x1andx2are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and havingN-1axes, whereNis number of axes in the shape determined according to broadcasting along the non-contracted axes. The returned array must have a data type determined by type-promotion.- Return type:
array
- Raises:
Exception – an exception should be raised in the following circumstances: - if the size of the axis over which to compute the dot product is not the same (before broadcasting) for both
x1andx2.
Notes
The contracted axis must not be broadcasted.
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Restricted
axisto only negative integers.- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.vector_norm(*args, **kwargs)[source]¶
Bases:
Protocol,GenericComputes the vector norm of a vector (or batch of vectors)
x.- Parameters:
x (array) – input array. Should have a floating-point data type.
axis (Optional[Union[int, Tuple[int, ...]]]) – If an integer,
axisspecifies the axis (dimension) along which to compute vector norms. If an n-tuple,axisspecifies the axes (dimensions) along which to compute batched vector norms. IfNone, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default:None.keepdims (bool) – If
True, the axes (dimensions) specified byaxismust be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see broadcasting). Otherwise, ifFalse, the axes (dimensions) specified byaxismust not be included in the result. Default:False.ord (Union[int, float, Literal[inf, -inf]]) –
order of the norm. The following mathematical norms must be supported:
ord
description
1
L1-norm (Manhattan)
2
L2-norm (Euclidean)
inf
infinity norm
(int,float >= 1)
p-norm
The following non-mathematical “norms” must be supported:
ord
description
0
sum(a != 0)
-1
1./sum(1./abs(a))
-2
1./sqrt(sum(1./abs(a)**2))
-inf
min(abs(a))
(int,float < 1)
sum(abs(a)**ord)**(1./ord)
Default:
2.
- Returns:
out – an array containing the vector norms. If
axisisNone, the returned array must be a zero-dimensional array containing a vector norm. Ifaxisis a scalar value (intorfloat), the returned array must have a rank which is one less than the rank ofx. Ifaxisis an-tuple, the returned array must have a rank which isnless than the rank ofx. Ifxhas a real-valued data type, the returned array must have a real-valued floating-point data type determined by type-promotion. Ifxhas a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision ofx(e.g., ifxiscomplex128, then the returned array must have afloat64data type).- Return type:
array
Notes
Changed in version 2022.12: Added complex data type support.
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.where(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns elements chosen from
x1orx2depending oncondition.- Parameters:
condition (array) – when
True, yieldx1_i; otherwise, yieldx2_i. Should have a boolean data type. Must be broadcast-compatible withx1andx2(see broadcasting).x1 (Union[array, int, float, complex, bool]) – first input array. Must be broadcast-compatible with
conditionandx2(see broadcasting).x2 (Union[array, int, float, complex, bool]) – second input array. Must be broadcast-compatible with
conditionandx1(see broadcasting).
- Returns:
out – an array with elements from
x1whereconditionisTrue, and elements fromx2elsewhere. The returned array must have a data type determined by type-promotion rules with the arraysx1andx2.- Return type:
array
Notes
At least one of
x1andx2must be an array.If either
x1orx2is a scalar value, the returned array must have a data type determined according to mixing-scalars-and-arrays.
Changed in version 2024.12: Added scalar argument support.
Changed in version 2024.12: Clarified that the
conditionargument should have a boolean data type.- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.zeros(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a new array having a specified
shapeand filled with zeros.- Parameters:
shape (Union[int, Tuple[int, ...]]) – output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be the default real-valued floating-point data type. Default:None.device (Optional[device]) – device on which to place the created array. Default:
None.
- Returns:
out – an array containing zeros.
- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶
- class array_api._2025_12.zeros_like(*args, **kwargs)[source]¶
Bases:
Protocol,GenericReturns a new array filled with zeros and having the same
shapeas an input arrayx.- Parameters:
x (array) – input array from which to derive the output array shape.
dtype (Optional[dtype]) – output array data type. If
dtypeisNone, the output array data type must be inferred fromx. Default:None.device (Optional[device]) – device on which to place the created array. If
deviceisNone, the output array device must be inferred fromx. Default:None.
- Returns:
out – an array having the same shape as
xand filled with zeros.- Return type:
array
- _abc_impl = <_abc._abc_data object>¶
- _is_protocol = True¶
- _is_runtime_protocol = True¶