zel*_*nka 97 python constants nan
大多数语言都有一个NaN常量,您可以使用它来为变量赋值NaN.python可以不使用numpy吗?
Mic*_*x2a 156
是的 - 使用float('nan').从Python 3.5开始,您也可以使用math.nan.
>>> a = float('nan')
>>> print(a)
nan
>>> print(a + 2)
nan
>>> a == a
False
>>> import math
>>> math.isnan(a)
True
>>> # Python 3.5+
>>> math.isnan(math.nan)
True
Run Code Online (Sandbox Code Playgroud)
该float(...)功能是不区分大小写-做float('NAN')或float('naN')或类似的事情也会起作用.
请注意,检查NaN的两个内容是否彼此相等将始终返回false.这部分是因为两个"非数字"的东西不能(严格地说)相互相等 - 请参阅IEEE754 NaN值返回false的所有比较的基本原理是什么?了解更多详情和信息.
相反,math.isnan(...)如果您需要确定值是否为NaN ,请使用.
此外,==当尝试将NaN存储在诸如list或dict(或使用自定义容器类型)的容器类型中时,对NaN值的操作的确切语义可能会导致细微的问题.有关详细信息,请参阅检查容器中的NaN存在.
您还可以使用Python的十进制模块构造NaN数字:
>>> from decimal import Decimal
>>> b = Decimal('nan')
>>> print(b)
NaN
>>> print(repr(b))
Decimal('NaN')
>>>
>>> Decimal(float('nan'))
Decimal('NaN')
>>>
>>> import math
>>> math.isnan(b)
True
Run Code Online (Sandbox Code Playgroud)
math.isnan(...) 也将使用Decimal对象.
但是,您无法在Python的分数模块中构造NaN数字:
>>> from fractions import Fraction
>>> Fraction('nan')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\fractions.py", line 146, in __new__
numerator)
ValueError: Invalid literal for Fraction: 'nan'
>>>
>>> Fraction(float('nan'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\fractions.py", line 130, in __new__
value = Fraction.from_float(numerator)
File "C:\Python35\lib\fractions.py", line 214, in from_float
raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
ValueError: Cannot convert nan to Fraction.
Run Code Online (Sandbox Code Playgroud)
顺便说一下,你也可以做float('Inf'),Decimal('Inf')或math.inf(3.5+)来分配无限的数字.(还看到math.isinf(...))
但是这样做Fraction('Inf')或者Fraction(float('inf'))是不允许的,将抛出一个异常,就像为NaN.
如果您想快速简便地检查数字是否既不是NaN也不是无限,您可以使用math.isfinite(...)Python 3.2+.
如果要对复数进行类似的检查,cmath模块包含与模块类似的一组函数和常量math:
cmath.isnan(...)cmath.isinf(...)cmath.isfinite(...) (Python 3.2+)cmath.nan(Python 3.6+;相当于complex(float('nan'), 0.0))cmath.nanj(Python 3.6+;相当于complex(0.0, float('nan')))cmath.inf(Python 3.6+;相当于complex(float('inf'), 0.0))cmath.infj(Python 3.6+;相当于complex(0.0, float('inf')))aba*_*ert 15
nan = float('nan')
Run Code Online (Sandbox Code Playgroud)
现在你有了常数,nan.
您可以类似地为decimal.Decimal创建NaN值:
dnan = Decimal('nan')
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以从“ inf-inf”获得NaN,并且可以从大于2e308的数字获得“ inf”,因此,我通常使用:
>>> inf = 9e999
>>> inf
inf
>>> inf - inf
nan
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
140892 次 |
| 最近记录: |