Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Return the type that results from applying the NumPy type promotion rules to the arguments in Python
The numpy.result_type() method returns the data type that results from applying NumPy's type promotion rules to the given arguments. This is useful for determining the output type of operations between different NumPy data types without actually performing the operation.
Syntax
numpy.result_type(*arrays_and_dtypes)
Parameters
The function accepts multiple arguments representing operands whose result type is needed. These can be:
- arrays_and_dtypes − Arrays, scalars, or data type strings/objects
How Type Promotion Works
NumPy follows specific rules for type promotion:
- When combining arrays and scalars, the array's type takes precedence
- The actual value of scalars is considered during promotion
- Integer types promote to float types when necessary
- Complex types have the highest precedence
Basic Examples
import numpy as np
# Scalar with array
result1 = np.result_type(2, np.arange(4, dtype='i1'))
print("Scalar + int8 array:", result1)
# Two scalars
result2 = np.result_type(5, 8)
print("Two integers:", result2)
# Data type strings
result3 = np.result_type('i4', 'c8')
print("int32 + complex64:", result3)
Scalar + int8 array: int8 Two integers: int64 int32 + complex64: complex128
Mixed Type Examples
import numpy as np
# Float and integer
result1 = np.result_type(3.8, 8)
print("Float + integer:", result1)
# Integer and float
result2 = np.result_type(5, 20.7)
print("Integer + float:", result2)
# Negative values
result3 = np.result_type(-8, 20.7)
print("Negative int + float:", result3)
# Float and negative integer
result4 = np.result_type(10.0, -4)
print("Float + negative int:", result4)
Float + integer: float64 Integer + float: float64 Negative int + float: float64 Float + negative int: float64
Practical Use Case
import numpy as np
# Check result type before creating arrays
arr1 = np.array([1, 2, 3], dtype='int32')
arr2 = np.array([1.5, 2.5, 3.5], dtype='float32')
result_type = np.result_type(arr1.dtype, arr2.dtype)
print("Result type for operation:", result_type)
# This helps in memory planning
result_array = np.empty(3, dtype=result_type)
print("Pre-allocated array dtype:", result_array.dtype)
Result type for operation: float64 Pre-allocated array dtype: float64
Conclusion
The numpy.result_type() function is essential for predicting data types in NumPy operations. It follows consistent promotion rules where floats take precedence over integers, and complex types rank highest in the hierarchy.
Advertisements
