Python 为什么不定义 NaN 呢?

2014-08-17 12:23:00 +08:00
 ZzFoo
判断一个变量是不是数字,还要先判断它是不是int或者float,感觉很啰嗦
不如直接一句 if n is NaN 来判断简洁,易读
7071 次点击
所在节点    问与答
8 条回复
roricon
2014-08-17 12:35:40 +08:00
https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy

你可以直接检测是否继承自numbers.Number类
from numbers import Number
>>>isinstance(1, Number)
>>>True

>>>isinstance(1.1111, Number)
>>>True
ZzFoo
2014-08-17 13:00:21 +08:00
@roricon 非常感谢
hahastudio
2014-08-17 13:24:00 +08:00
你也许需要 float("nan") 和 math.isnan(x)
>>> float("nan")
nan
>>> nan = float("nan")
>>> import math
>>> math.isnan(nan)
True
>>> math.isnan(1)
False
>>> math.isnan(nan + 1)
True
ZzFoo
2014-08-17 15:32:35 +08:00
@hahastudio 谢谢啊。但是math.isnan()只接受float类型做参数,又怎么用它来判断变量类型呢
msg7086
2014-08-17 15:49:35 +08:00
@ZzFoo 我觉得上面写得很清楚了啊, math.isnan(float("nan"))
ZzFoo
2014-08-17 16:08:47 +08:00
@msg7086 float()可以把纯数字的字符串和‘nan’这个字符串转换成float型,但是没法转换其他的字符串。

>>> float('123')
123.0
>>> float('nan')
nan
>>> float('nana')
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>
float('nana')
ValueError: could not convert string to float: 'nana'
hahastudio
2014-08-17 16:45:23 +08:00
啊,Python 喜欢先试,后果另说
你大可以
try:
....n = float(input_str) # e.g. input_str = "123"
except ValueError:
....n = float("nan") # or any other default value you want

对了,作为豆知识
>>> float("inf")
inf
>>> float("-inf")
-inf

对了,突然想起来,也许这个才是 LZ 最想要的:
>>> from decimal import *
>>> setcontext(ExtendedContext)
>>> nan = Decimal("I'm not a number!")
>>> nan
Decimal('NaN')
>>> print nan
NaN

它还能做到更多:
>>> inf = Decimal(1) / Decimal(0)
>>> print inf
Infinity
>>> neginf = Decimal(-1) / Decimal(0)
>>> print neginf
-Infinity
>>> print inf + neginf
NaN
>>> print inf * neginf
-Infinity
>>> print 2 * inf
Infinity
>>> print 1 + nan
NaN
ZzFoo
2014-08-17 18:11:05 +08:00
@hahastudio 刚看了一下手册,发现Decimal类有一个is_nan()的方法。谢谢啦~

>>> Decimal('anything').is_nan()
True
>>> Decimal(1).is_nan()
False

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/128354

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX