英文:
python function or operation that returns float("nan")
问题
IEEE浮点数算术标准(IEEE 754)要求存在一个称为nan(不是一个数)的float(或两个...)。
有两种方法可以得到nan(我知道的)
nan = float("nan")
# 或者
from math import nan
但是在标准库中有没有我可以对floats执行的数学函数返回nan呢?
像math.sqrt(-1)(等等)这样的显而易见的想法不会返回nan,而是引发ValueError: math domain error。
或者nans只是用于数据中值缺失的情况,不应该由函数返回?
(有没有什么可以返回math.inf的东西?同样,显而易见的1/0会引发ZeroDivisionError)。
英文:
the IEEE Standard for Floating-Point Arithmetic (IEEE 754) requires the existence of a float (or two...) that is called nan (not a number).
there are two ways to get nan (that i know of)
nan = float("nan")
# or
from math import nan
but is there a mathematical function i can perform on floats in the standard library that returns nan?
the obvious ideas like math.sqrt(-1) (and similar) do not return nan but raise ValueError: math domain error.
or are nans only meant for data where values are missing and are never supposed to be returned by a function?
(is there also something that returns math.inf? again, the obvious 1/0 raises a ZeroDivisionError).
答案1
得分: 4
math.inf - math.inf 得到 nan。
(1e308 + 1e308 或只是 1e309 得到 inf.)
英文:
math.inf - math.inf gives nan.
(1e308 + 1e308 or just 1e309 give inf.)
答案2
得分: 3
生成 NaN:
math.inf * 0结果为nan
> (+∞) × 0 = NaN
-
math.inf之间的+(符号相反)和/(任意符号)运算 -
以及奖励情况:生成两个
nan:In [576]: divmod(math.inf, 1) Out[576]: (nan, nan)
英文:
Generating NaN:
math.inf * 0results tonan
> (+∞) × 0 = NaN
-
+(on opposite signs) and/(on any sign) operations betweenmath.infs -
and bonus case: generating 2
nans:In [576]: divmod(math.inf, 1) Out[576]: (nan, nan)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论