0
0
NumPydata~5 mins

Integer types (int8, int16, int32, int64) in NumPy

Choose your learning style9 modes available
Introduction

Integer types let us store whole numbers in different sizes. This helps save memory and match the data we have.

When you want to save memory by using smaller number sizes for whole numbers.
When reading data from files that specify integer sizes, like int16 or int32.
When you need to control the range of numbers to avoid errors or overflow.
When working with hardware or systems that require specific integer sizes.
When you want to optimize performance by choosing the right integer type.
Syntax
NumPy
numpy.int8
numpy.int16
numpy.int32
numpy.int64

These are data types in numpy for integers of different sizes.

int8 uses 8 bits, int16 uses 16 bits, int32 uses 32 bits, and int64 uses 64 bits.

Examples
This creates a numpy array of 8-bit integers.
NumPy
import numpy as np
x = np.array([10, 20, 30], dtype=np.int8)
This creates a numpy array of 16-bit integers.
NumPy
y = np.array([1000, 2000, 3000], dtype=np.int16)
This creates a numpy array of 32-bit integers.
NumPy
z = np.array([100000, 200000, 300000], dtype=np.int32)
This creates a numpy array of 64-bit integers for very large numbers.
NumPy
w = np.array([10000000000, 20000000000, 30000000000], dtype=np.int64)
Sample Program

This program creates numpy arrays with different integer types and prints their values and types. It shows how each integer type can hold different ranges of numbers.

NumPy
import numpy as np

# Create arrays with different integer types
arr_int8 = np.array([127, -128, 0], dtype=np.int8)
arr_int16 = np.array([32767, -32768, 0], dtype=np.int16)
arr_int32 = np.array([2147483647, -2147483648, 0], dtype=np.int32)
arr_int64 = np.array([9223372036854775807, -9223372036854775808, 0], dtype=np.int64)

print('int8 array:', arr_int8)
print('int16 array:', arr_int16)
print('int32 array:', arr_int32)
print('int64 array:', arr_int64)

# Show the data types
print('Data type of arr_int8:', arr_int8.dtype)
print('Data type of arr_int16:', arr_int16.dtype)
print('Data type of arr_int32:', arr_int32.dtype)
print('Data type of arr_int64:', arr_int64.dtype)
OutputSuccess
Important Notes

int8 can store numbers from -128 to 127.

int16 can store numbers from -32768 to 32767.

Using the wrong integer size can cause overflow or data loss.

Summary

Integer types in numpy let you choose how much memory to use for whole numbers.

Different sizes (int8, int16, int32, int64) store different ranges of numbers.

Choosing the right integer type helps save memory and avoid errors.