用 Numpy 测试元素是否为正无穷或负无穷
若要按元素测试正无穷或负无穷,请在 Python Numpy 中使用 numpy.isinf() 方法。它将返回与 x 形状相同的布尔数组,其中 x == +/- 无穷时为 True,否则为 False。
NumPy 使用 IEEE 754 二进制浮点数算术标准。当第一个参数为标量时提供第二个参数,或如果第一个和第二个参数形状不同,则会产生错误。
步骤
首先,导入所需的库 −
import numpy as np
若要按元素测试正无穷或负无穷,请在 Python Numpy 中使用 numpy.isinf() 方法。
检查数字 −
print("Infinite? ", np.isinf(1)) print("
Infinite? ", np.isinf(0))
检查浮点数 −
print("
Infinite? ", np.isinf(14.)) print("
Infinite? ", np.isinf(3.6))
检查 NaN −
print("
Infinite? ", np.isinf(np.nan)) print("
Infinite? ", np.isinf(np.NAN))
检查无穷大 −
print("
Infinite? ", np.isinf(np.inf)) print("
Infinite? ", np.isinf(np.NINF))
检查对数 −
print("
Infinite? ", np.isinf(np.log(1))) print("
Infinite? ", np.isinf(np.log(2)))
示例
import numpy as np # To test element-wise for positive or negative infinity, use the numpy.isinf() method in Python Numpy # Checking for numbers print("Infinite? ", np.isinf(1)) print("
Infinite? ", np.isinf(0)) # Checking for float print("
Infinite? ", np.isinf(14.)) print("
Infinite? ", np.isinf(3.6)) # Checking for NaN print("
Infinite? ", np.isinf(np.nan)) print("
Infinite? ", np.isinf(np.NAN)) # Checking for infinity print("
Infinite? ", np.isinf(np.inf)) print("
Infinite? ", np.isinf(np.NINF)) # Checking for log print("
Infinite? ", np.isinf(np.log(1))) print("
Infinite? ", np.isinf(np.log(2)))
输出
Infinite? False Infinite? False Infinite? False Infinite? False Infinite? False Infinite? False Infinite? True Infinite? True Infinite? False Infinite? False
广告