Sahaj.blogs
5 Feb 2024 · StudyPhase 3 · NumPy

NumPy · dtypes

NumPy dtypes (int32, int64, float32, float64, bool), memory per element, casting with astype, and silent integer overflow.

Every element of an array shares one dtype, and the dtype decides how many bytes each element takes.

dtypebytestypical use
int648default integers on most platforms
int324compact integers
float648default floats
float324deep learning (half the memory)
bool1masks
  • astype converts and returns a copy. Going from float to int truncates toward zero.
  • Unlike Python ints, NumPy ints are fixed width, so they wrap around on overflow. That’s the C++ lesson again.
  • float32 stores fewer significant digits than float64.
import numpy as np

x = np.array([1, 2, 3])
y = np.array([1.5, 2.7, -3.9])
print(x.dtype, y.dtype, x.itemsize, y.itemsize)

print(y.astype(np.int64))                     # truncates toward zero
small = np.array([1.0, 2.0, 3.0], dtype=np.float32)
print(small.dtype, small.nbytes, "bytes vs", small.astype(np.float64).nbytes)

i8 = np.array([120, 127], dtype=np.int8)
print(i8 + np.int8(10))                       # wraps around!
print(np.iinfo(np.int8), sep="")
print(np.float32(0.1) == np.float64(0.1), np.finfo(np.float32).eps)

Output:

int64 float64 8 8
[ 1  2 -3]
float32 12 bytes vs 24
[-126 -119]
Machine parameters for int8
---------------------------------------------------------------
min = -128
max = 127
---------------------------------------------------------------

False 1.1920929e-07

#numpy#dtypes

Sources

  1. Data types — NumPy
  2. Data type objects (dtype) — NumPy
  3. numpy.ndarray.astype — NumPy