Return True if cast between scalar and data type can occur according to the casting rule in Python


The numpy.can_cast() method returns True if scalar and data type can occur according to the casting rule. The 1st parameter is the scalar or data type or array to cast from. The 2nd parameter is the data type to cast to.

Steps

At first, import the required library −

import numpy as np

Checking if scalar and data type can occur according to the casting rule. −

print("Checking with can_cast() method in Numpy\n")
print("Result...",np.can_cast(20, 'i1'))
print("Result...",np.can_cast(280, 'i1'))
print("Result...",np.can_cast(80, 'u1'))
print("Result...",np.can_cast(300.7, np.float32))
print("Result...",np.can_cast(120.6, np.float64))
print("Result...",np.can_cast(7.2e100, np.float32))
print("Result...",np.can_cast(6.5e100, np.float64))

Example

import numpy as np

# The numpy.can_cast() method returns True if scalar and data type can occur according to the casting rule.
# The 1st parameter is the scalar or data type or array to cast from.
# The 2nd parameter is the data type to cast to.

print("Checking with can_cast() method in Numpy\n")
print("Result...",np.can_cast(20, 'i1'))
print("Result...",np.can_cast(280, 'i1'))
print("Result...",np.can_cast(80, 'u1'))
print("Result...",np.can_cast(300.7, np.float32))
print("Result...",np.can_cast(120.6, np.float64))
print("Result...",np.can_cast(7.2e100, np.float32))
print("Result...",np.can_cast(6.5e100, np.float64))

Output

Checking with can_cast() method in Numpy

Result... True
Result... False
Result... True
Result... True
Result... True
Result... False
Result... True

Updated on: 28-Feb-2022

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements