在所有版本的Python中,我们可以表示无穷大和NaN(“非数字”),如下所示:
pos_inf = float('inf') # 正无穷大 neg_inf = float('-inf') # 负无穷大 not_a_num = float('nan') # NaN ("not a number")
在Python 3.5及更高版本中,我们还可以使用定义的常量math.inf和math.nan:
pos_inf = math.inf neg_inf = -math.inf not_a_num = math.nan
字符串表示形式显示为inf和-inf和nan:
pos_inf, neg_inf, not_a_num # 输出:(inf,-inf,nan)
我们可以使用以下isinf方法测试正无穷或负无穷大:
math.isinf(pos_inf) # 出:真 math.isinf(neg_inf) # 出:真
我们可以通过直接比较专门测试正无穷大或负无穷大:
pos_inf == float('inf') # 或== math.infin Python 3.5+ # 出:真 neg_inf == float('-inf') # 或== -math.inf在Python 3.5+ # 出:真 neg_inf == pos_inf # 出:错误
Python 3.2和更高版本还允许检查有限性:
math.isfinite(pos_inf) # 出:错误 math.isfinite(0.0) # 出:真
比较运算符按预期的正负无穷工作:
import sys sys.float_info.max # 输出:1.7976931348623157e + 308(这取决于系统) pos_inf > sys.float_info.max # 出:真 neg_inf < -sys.float_info.max # 出:真
但是,如果算术表达式产生的值大于可表示为的最大值float,则它将变为无穷大:
pos_inf == sys.float_info.max * 1.0000001 # 出:真 neg_inf == -sys.float_info.max * 1.0000001 # 出:真
但是,被零除不会给出无穷大的结果(或在适当情况下为负无穷大),而是会引发ZeroDivisionError异常。
try: x = 1.0 / 0.0 print(x) except ZeroDivisionError: print("Division by zero") # 出:被零除
无穷大的算术运算只会给出无限的结果,或者有时是NaN:
-5.0 * pos_inf == neg_inf # 出:真 -5.0 * neg_inf == pos_inf # 出:真 pos_inf * neg_inf == neg_inf # 出:真 0.0 * pos_inf # 出:南 0.0 * neg_inf # 出:南 pos_inf / pos_inf # 出:南
NaN永远不等于任何事物,甚至不等于任何事物。我们可以使用以下isnan方法进行测试:
not_a_num == not_a_num # 出:错误 math.isnan(not_a_num) Out: True
NaN总是比较为“不等于”,但决不小于或大于:
not_a_num != 5.0 # 或任何随机值 # 出:真 not_a_num > 5.0 or not_a_num < 5.0 or not_a_num == 5.0 # 出:错误
NaN上的算术运算始终给出NaN。这包括乘以-1:没有“负NaN”。
5.0 * not_a_num # 出:南 float('-nan') # 出:南
-math.nan # 出:南
floatNaN和infinity的旧版本与Python 3.5+math库常量之间有一个微妙的区别:
math.inf is math.inf,math.nanis math.nan # 出:(正确,正确) float('inf') is float('inf'), float('nan') is float('nan') # 出:(错误,错误)