NaN, Not a Number, 非数. 它即不是无穷大, 也不是无穷小, 而是python/numpy/... 觉得无法计算时返回的一个符号(自己的推测, 未考证(TODO)).
import numpy as np
无穷大减无穷大会导致NaN
a = np.infty
print a - a
nan
print a * a, a * a - a
inf nan
无穷大乘以0或无穷小或除以无穷大会导致NaN
print a * 0
nan
print a * 1/ a
nan
print a / a
nan
print a / 1
inf
print a / 1
inf
总结起来就是, 涉及到无穷大的四则运算, 若无法确定运算结果仍为无穷大, 那么运算结果就是一个NaN.
另外很明显的是:
有NaN参与的运算, 其结果也一定是NaN
b = np.nan
print b + 1
nan
print b - b
nan
NaN != NaN
print b == b
False
利用这个性质可以判断数组中是否含有NaN:
def has_nan(x):
test = x != x
return np.sum(test) > 0
也可以使用系统api:
import math
val = float('nan')
if math.isnan(val):
print('Detected NaN')
import pdb; pdb.set_trace() # Break into debugger to look around
markdown由jupyter notebook生成. [notebook](https://github.com/dengdan/blog_posts/blob/master/python/NaN.ipynb)