astype¶
- astype(x: array, dtype: dtype, /, *, copy: bool = True, device: device | None = None) array ¶
Copies an array to a specified data type irrespective of Type Promotion Rules rules.
Note
Casting floating-point
NaN
andinfinity
values 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
True
must cast to a real-valued number equal to1
, and a value ofFalse
must cast to a real-valued number equal to0
.When casting a boolean input array to a complex floating-point data type, a value of
True
must cast to a complex number equal to1 + 0j
, and a value ofFalse
must cast to a complex number equal to0 + 0j
.Note
When casting a real-valued input array to
bool
, a value of0
must cast toFalse
, and a non-zero value must cast toTrue
.When casting a complex floating-point array to
bool
, a value of0 + 0j
must 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
dtype
matches the data type of the input arrayx
. IfTrue
, a newly allocated array must always be returned. IfFalse
and the specifieddtype
matches 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
device
isNone
, the output array device must be inferred fromx
. Default:None
.
- Returns:
out (array) – an array having the specified data type. The returned array must have the same shape as
x
.
Notes
Changed in version 2022.12: Added complex data type support.
Changed in version 2023.12: Added device keyword argument support.