什么是inf和nan?

Ser*_*ial 35 python python-2.7

只是一个我很困惑的问题

所以我一直在搞乱,float('inf')并想知道它用于什么.

另外我注意到,如果我添加-inf + inf我得到的nan是与零相同或不同.

我对这两个值的用途感到困惑.

另外,当我这样nan - inf做时,我不明白-infnan知道这一切都很简单,但我偶然发现它们并且不知道它们做了什么.

Vol*_*ity 46

inf是无穷大 - 一个大于任何其他值的值.-inf因此小于任何其他值.

nan代表非数字,这不等于0.

尽管正负无穷大可以说是对称的0,但对于任何值都可以说同样的n,这意味着增加两个产量的结果nan.在这个math.se问题中讨论了这个想法.

因为nan(字面上)不是数字,你不能用它做算术,所以第二次操作的结果也不是数字(nan)


Tim*_*ker 6

nan表示“不是数字”,这是一个浮点值,如果您执行的计算结果不能表示为数字。您执行的任何计算也NaN将导致NaN.

inf 意味着无穷大。

例如:

>>> 2*float("inf")
inf
>>> -2*float("inf")
-inf
>>> float("inf")-float("inf")
nan
Run Code Online (Sandbox Code Playgroud)


U2E*_*EF1 6

Inf是无穷大,它是一个“比所有其他数字都大”的数字。尝试从中减去任何你想要的东西,它不会变小。所有数字都是< Inf. -Inf相似,但比一切都小。

NaN表示非数字。如果你尝试进行没有意义的计算,你会得到NaN. Inf - Inf就是这样一种计算。通常NaN仅用于表示某些数据丢失。


dev*_*ull 5

你说:

当我这样做时,nan - inf我不明白,-inf我明白nan

这是因为任何包含NaN作为操作数的操作都会返回NaN.

与 的比较NaN将返回无序结果

>>> float('Inf') == float('Inf')
True
>>> float('NaN') == float('NaN')
False
Run Code Online (Sandbox Code Playgroud)


小智 5

我使用 inf/-inf 作为初始值来查找测量的最小值/最大值。假设您使用传感器测量温度,并且想要跟踪最低/最高温度。传感器可能会提供有效的温度,也可能会损坏。伪代码:

# initial value of the temperature
t = float('nan')          
# initial value of minimum temperature, so any measured temp. will be smaller
t_min = float('inf')      
# initial value of maximum temperature, so any measured temp. will be bigger
t_max = float('-inf')     
while True:
    # measure temperature, if sensor is broken t is not changed
    t = measure()     
    # find new minimum temperature
    t_min = min(t_min, t) 
    # find new maximum temperature
    t_max = max(t_max, t) 
Run Code Online (Sandbox Code Playgroud)

上面的代码之所以有效,是因为 inf/-inf/nan 对于 min/max 操作有效,因此不需要处理异常。