为什么“不是数字"在 Python/Numpy 中转换为布尔值时值等于 True 吗? [英] Why do "Not a Number" values equal True when cast as boolean in Python/Numpy?
问题描述
当将 NumPy Not-a-Number 值转换为布尔值时,它变为 True,例如如下.
<预><代码>>>>将 numpy 导入为 np>>>布尔(np.nan)真的这与我的直觉预期完全相反.这种行为背后是否有合理的原则?
(我怀疑在 Octave 中可能会发生同样的行为.)
这绝不是 NumPy 特定的,但与 Python 处理 NaN 的方式一致:
在[1]中:bool(float('nan'))输出[1]:真
这些规则在文档中有详细说明.
我认为可以合理地论证 NaN 的真值应该是 False.但是,这不是该语言目前的工作方式.
When casting a NumPy Not-a-Number value as a boolean, it becomes True, e.g. as follows.
>>> import numpy as np
>>> bool(np.nan)
True
This is the exact opposite to what I would intuitively expect. Is there a sound principle underlying this behaviour?
(I suspect there might be as the same behaviour seems to occur in Octave.)
This is in no way NumPy-specific, but is consistent with how Python treats NaNs:
In [1]: bool(float('nan'))
Out[1]: True
The rules are spelled out in the documentation.
I think it could be reasonably argued that the truth value of NaN should be False. However, this is not how the language works right now.
这篇关于为什么“不是数字"在 Python/Numpy 中转换为布尔值时值等于 True 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!