0
0
NumPydata~5 mins

Type promotion in operations in NumPy

Choose your learning style9 modes available
Introduction

Type promotion helps numpy decide the best data type to use when combining different types in math operations. It keeps your results accurate and avoids errors.

Adding an integer array to a float array to get a float result.
Multiplying a boolean array with an integer array to get integers.
Combining arrays of different sizes and types in calculations.
Performing operations on arrays with mixed data types like int32 and int64.
Ensuring results keep decimal points when mixing integers and floats.
Syntax
NumPy
result = array1 + array2  # numpy automatically promotes types

Numpy automatically chooses a common data type that can hold all values without losing information.

Type promotion happens in all arithmetic and logical operations between arrays.

Examples
Adding int32 and float64 arrays results in a float64 array.
NumPy
import numpy as np

arr1 = np.array([1, 2, 3], dtype=np.int32)
arr2 = np.array([1.5, 2.5, 3.5], dtype=np.float64)
result = arr1 + arr2
print(result)
print(result.dtype)
Multiplying boolean and int8 arrays promotes booleans to int8.
NumPy
import numpy as np

arr1 = np.array([True, False, True], dtype=bool)
arr2 = np.array([10, 20, 30], dtype=np.int8)
result = arr1 * arr2
print(result)
print(result.dtype)
Adding int16 and int32 arrays promotes to int32 to hold larger values.
NumPy
import numpy as np

arr1 = np.array([1, 2, 3], dtype=np.int16)
arr2 = np.array([100000], dtype=np.int32)
result = arr1 + arr2
print(result)
print(result.dtype)
Sample Program

This program shows how numpy promotes types when adding integers and floats, and when multiplying booleans and integers.

NumPy
import numpy as np

# Create arrays with different types
int_arr = np.array([1, 2, 3], dtype=np.int32)
float_arr = np.array([0.5, 1.5, 2.5], dtype=np.float64)
bool_arr = np.array([True, False, True], dtype=bool)

# Add int and float arrays
add_result = int_arr + float_arr

# Multiply bool and int arrays
mul_result = bool_arr * int_arr

# Print results and their types
print('Add result:', add_result)
print('Add result type:', add_result.dtype)
print('Multiply result:', mul_result)
print('Multiply result type:', mul_result.dtype)
OutputSuccess
Important Notes

Type promotion ensures no data is lost during operations.

Be aware that promotion can increase memory use if types change to larger ones.

You can check the resulting data type with the dtype attribute.

Summary

Type promotion automatically picks a common data type for operations.

It helps keep results accurate when mixing types like int and float.

Always check the result's dtype to understand the output type.