[英]difference between np.inf and float('Inf')
NumPy np.inf
和float('Inf')
之间有什么区别吗? float('Inf') == np.inf
返回True
,所以看起来它们是可以互换的,因此我想知道为什么 NumPy 定义了自己的“inf”常量,我什么时候应该使用一个常量而不是另一个(考虑样式也有顾虑)?
除了与math.inf
和float('inf')
具有相同的值:
>>> import math
>>> import numpy as np
>>> np.inf == float('inf')
True
>>> np.inf == math.inf
True
它也有相同的类型:
>>> import numpy as np
>>> type(np.inf)
float
>>> type(np.inf) is type(float('inf'))
float
这很有趣,因为 NumPy 也有它自己的浮点类型:
>>> np.float32(np.inf)
inf
>>> type(np.float32(np.inf))
numpy.float32
>>> np.float32('inf') == np.inf # nevertheless equal
True
因此它与math.inf
和float('inf')
具有相同的值和相同的类型,这意味着它是可以互换的。
np.inf
原因输入更少:
np.inf
(6 个字符)math.inf
(8 个字符;python 3.5 中的新内容)float('inf')
(12 个字符) 这意味着如果您已经导入了 NumPy,与float('inf')
(或math.inf
)相比,每次出现您可以节省 6(或 2)个字符。
因为更容易记住。
至少对我来说,记住np.inf
比我需要用字符串调用float
容易得多。
此外,NumPy 还为无穷大定义了一些额外的别名:
np.Inf np.inf np.infty np.Infinity np.PINF
它还定义了负无穷大的别名:
np.NINF
同样对于nan
:
np.nan np.NaN np.NAN
常数就是常数
这一点基于 CPython,在另一个 Python 实现中可能完全不同。
一个float
CPython 实例需要 24 个字节:
>>> import sys >>> sys.getsizeof(np.inf) 24
如果您可以重用同一个实例,与创建大量新实例相比,您可能会节省大量内存。 当然,如果您创建自己的inf
常量,这一点是inf
但如果您不这样做:
a = [np.inf for _ in range(1000000)] b = [float('inf') for _ in range(1000000)]
b
将使用比a
多 24 * 1000000 字节(~23 MB)的内存。
访问常量比创建变量快。
%timeit np.inf 37.9 ns ± 0.692 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) %timeit float('inf') 232 ns ± 13.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %timeit [np.inf for _ in range(10000)] 552 µs ± 15.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit [float('inf') for _ in range(10000)] 2.59 ms ± 78.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
当然,您可以创建自己的常量来反驳这一点。 但是如果 NumPy 已经为你做了那又何必呢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.