“`plaintext 返回浮点数(“nan”)的Python函数或操作 “`

huangapple go评论77阅读模式
英文:

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 * 0 results to nan

> (+∞) × 0 = NaN

  • + (on opposite signs) and / (on any sign) operations between math.infs

  • and bonus case: generating 2 nans:

    In [576]: divmod(math.inf, 1)
    Out[576]: (nan, nan)
    

huangapple
  • 本文由 发表于 2023年2月23日 22:59:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定