为什么 Python 中没有 Inf、-Inf 和 NaN 关键字?
Why aren't Inf, -Inf and NaN keywords in Python?
在PEP 754的拒稿通知中,写着:
This PEP has been rejected. After sitting open for four years, it has
failed to generate sufficient community interest.
Several ideas of this PEP were implemented for Python 2.6.
float('inf') and repr(float('inf')) are now guaranteed to work on
every supported platform with IEEE 754 semantics. However the
eval(repr(float('inf'))) roundtrip is still not supported unless you
define inf and nan yourself:
>>> inf = float('inf')
>>> inf, 1E400
(inf, inf)
>>> neginf = float('-inf')
>>> neginf, -1E400
(-inf, -inf)
>>> nan = float('nan')
>>> nan, inf * 0.
(nan, nan)
这似乎是说 Python 中没有对 Inf、NaN 和 -Inf 的原生支持,所提供的示例是准确的!但是,它不必要地冗长:
$ python2.7
>>> 1e400
inf
>>> 1e400 * 0
nan
>>> -1e400 * 0
nan
>>> -1e400
-inf
$ python3
>>> 1e400
inf
>>> 1e400 * 0
nan
>>> -1e400 * 0
nan
>>> -1e400
-inf
这些是数字 1 * 10 ^ 400 的 规范 表示。语法中默认不存在名称 inf
和 nan
,但如果它们在表示中存在,那么为什么 inf
和 nan
关键字不是?
我不是在问为什么 PEP 被拒绝,因为它是基于意见的。
我的猜测是没有人想要不必要地弄乱命名空间。
如果你想做数学,你仍然可以做:
import math
print(math.inf)
print(-math.inf)
print(math.nan)
输出:
inf
-inf
nan
你可以使用
浮动('inf')
np.nan
在PEP 754的拒稿通知中,写着:
This PEP has been rejected. After sitting open for four years, it has failed to generate sufficient community interest.
Several ideas of this PEP were implemented for Python 2.6. float('inf') and repr(float('inf')) are now guaranteed to work on every supported platform with IEEE 754 semantics. However the eval(repr(float('inf'))) roundtrip is still not supported unless you define inf and nan yourself:
>>> inf = float('inf') >>> inf, 1E400 (inf, inf) >>> neginf = float('-inf') >>> neginf, -1E400 (-inf, -inf) >>> nan = float('nan') >>> nan, inf * 0. (nan, nan)
这似乎是说 Python 中没有对 Inf、NaN 和 -Inf 的原生支持,所提供的示例是准确的!但是,它不必要地冗长:
$ python2.7
>>> 1e400
inf
>>> 1e400 * 0
nan
>>> -1e400 * 0
nan
>>> -1e400
-inf
$ python3
>>> 1e400
inf
>>> 1e400 * 0
nan
>>> -1e400 * 0
nan
>>> -1e400
-inf
这些是数字 1 * 10 ^ 400 的 规范 表示。语法中默认不存在名称 inf
和 nan
,但如果它们在表示中存在,那么为什么 inf
和 nan
关键字不是?
我不是在问为什么 PEP 被拒绝,因为它是基于意见的。
我的猜测是没有人想要不必要地弄乱命名空间。
如果你想做数学,你仍然可以做:
import math
print(math.inf)
print(-math.inf)
print(math.nan)
输出:
inf
-inf
nan
你可以使用
浮动('inf')
np.nan