在Python中检查数值是否为无穷大或NaN
在这篇文章中,我们将检查给定值是否为NaN或Infinity。这可以通过数学模块来完成。让我们看看如何详细地检查每个值。
检查数值是否为NaN
NaN代表 “Not a Number”,它是一种数字数据类型,用来代表数学上未定义或无法表示的值。它们有各种例子,例如
- 0/0是未定义的,用NaN来表示。
- Sqrt(-ve number)不能作为实数存储,所以用NaN来表示它。
- 对数(-ve数)不能作为实数存储,所以用NaN来表示它。
- 一个数字< -1 or number >1的反sin或反cos< -1 or number >也是NaN。 < -1 or number >
- inf也会导致NaN。
由于NaN本身就是一个类型,所以它被用来分配那些还没有计算出数值的变量。
方法1 。为了检查NaN,我们可以使用math.isan() 函数,因为NaN不能用==运算符测试。
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")
输出
x contains nan x == nan
方法2: NaN不等于NaN,因此我们可以利用这个属性来检查NaN。下面的代码演示了这一点。
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
检查该值是否是无穷大
方法一:在python中检查无限,使用的函数是math.isinf(),它只检查无限的情况。为了区分正的和负的无限,我们可以添加更多的逻辑来检查数字是否大于0或小于0,代码显示了这一点。
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
方法2: Numpy还暴露了两个API来检查正负无限。这两个API是np.isneginf() 和 np.isposinf() 。
# 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]
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com