📜  检查Python的值是无穷大还是 NaN

📅  最后修改于: 2022-05-13 01:55:31.349000             🧑  作者: Mango

检查Python的值是无穷大还是 NaN

在本文中,我们将检查给定的值是 NaN 还是 Infinity。这可以使用 math 模块来完成。让我们看看如何详细检查每个值。

检查值是否为 NaN

NaN 代表“非数字”,它是一种数字数据类型,用作数学上未定义或无法表示的值的代理。有各种各样的例子,比如——

  1. 0/0 未定义,NaN 用于表示它。
  2. Sqrt(-ve number) 不能存储为实数,因此使用 NaN 来表示它。
  3. Log(-ve number) 不能存储为实数,因此使用 NaN 来表示它。
  4. 数 < -1 或数 > 1 的反正弦或反余弦也是 NaN。
  5. 0 * inf 也会导致 NaN。

由于 NaN 本身就是类型,它用于分配尚未计算值的变量。

方法 1 :要检查 NaN,我们可以使用math.isnan()函数,因为 NaN 无法使用 ==运算符进行测试。

Python3
import math
 
 
x = math.nan
print(f"x contains {x}")
 
# checks if variable is equal to NaN
if(math.isnan(x)):
    print("x == nan")
else:
    print("x != nan")


Python3
import math
 
 
def isNan(number):
     
    # This function compares number to itself.
    # NaN != NaN and therefore it will return
    # true if the number is Nan
    return number != number
 
# Driver Code 
x = math.nan
print(isNan(x))


Python3
import math
 
# Function checks if negative or
# positive infinite.
def check(x):
   
    if(math.isinf(x) and x > 0):
        print("x is Positive inf")
     
    elif(math.isinf(x) and x < 0):
        print("x is negative inf")
     
    else:
        print("x is not inf")
 
 
# Creating inf using math module.
number = math.inf
check(number)
 
number = -math.inf
check(number)


Python3
# pip install numpy
import numpy as np
 
print(np.isneginf([np.inf, 0, -np.inf]))
print(np.isposinf([np.inf, 0, -np.inf]))


输出

x contains nan
x == nan

方法 2: NaN 不等于 NaN,因此我们可以利用此属性来检查 NaN。下面的代码演示了它。

蟒蛇3

import math
 
 
def isNan(number):
     
    # This function compares number to itself.
    # NaN != NaN and therefore it will return
    # true if the number is Nan
    return number != number
 
# Driver Code 
x = math.nan
print(isNan(x))


输出
True

检查值是否为无穷大

方法1:在Python检查无穷大,使用的函数是math.isinf() ,它只检查无穷大。为了区分正无穷大和负无穷大,我们可以添加更多的逻辑来检查数字是大于 0 还是小于 0。代码显示了这一点。

蟒蛇3

import math
 
# Function checks if negative or
# positive infinite.
def check(x):
   
    if(math.isinf(x) and x > 0):
        print("x is Positive inf")
     
    elif(math.isinf(x) and x < 0):
        print("x is negative inf")
     
    else:
        print("x is not inf")
 
 
# Creating inf using math module.
number = math.inf
check(number)
 
number = -math.inf
check(number)


输出

x is Positive inf
x is negative inf

方法二: Numpy还暴露了两个API来检查正负无穷大。这是np.isneginf() np.isposinf()

蟒蛇3

# pip install numpy
import numpy as np
 
print(np.isneginf([np.inf, 0, -np.inf]))
print(np.isposinf([np.inf, 0, -np.inf]))

输出

[False False  True]
[ True False False]