如何在Python中表示整数的最小值和最大值?在Java中,我们有Integer。MIN_VALUE和Integer.MAX_VALUE。


请参见:Python中的最大浮点数是什么?


当前回答

下面给出的代码将帮助您。 对于最大值,可以使用sys。对于Maxsize和minimum,您可以对相同的值进行否定并使用它。

import sys 

ni=sys.maxsize
print(ni)

其他回答

下面给出的代码将帮助您。 对于最大值,可以使用sys。对于Maxsize和minimum,您可以对相同的值进行否定并使用它。

import sys 

ni=sys.maxsize
print(ni)

如果你想要数组或列表索引的最大值(相当于C/ c++中的size_t),你可以使用numpy:

np.iinfo(np.intp).max

这与sys相同。Maxsize的优点是你不需要import sys。

如果你想在机器上为本机int设置max:

np.iinfo(np.intc).max

您可以在doc中查看其他可用的类型。

对于浮点数,你也可以使用sys.float_info.max。

Python 3

在Python 3中,这个问题不适用。普通int类型是无界的。

然而,您实际上可能正在寻找有关当前解释器的单词大小的信息,在大多数情况下,这将与机器的单词大小相同。该信息在Python 3中仍然可用为sys。Maxsize,这是一个带符号的单词所能表示的最大值。等效地,它是最大的可能列表或内存序列的大小。

通常,无符号单词所能表示的最大值为sys。Maxsize * 2 + 1,一个字的比特数将是math.log2(sys. log2)。maxsize * 2 + 2)。更多信息请看这个答案。

Python 2

在Python 2中,纯int值的最大值可以通过sys.maxint获得:

>>> sys.maxint  # on my system, 2**63-1
9223372036854775807

您可以使用-sys来计算最小值。Maxint - 1如文档中所示。

一旦超过这个值,Python就会无缝地从普通整数切换到长整数。所以大多数时候,你不需要知道它。

如果你只需要一个比其他所有数字都大的数字,你可以使用

float('inf')

小数:以类似的方式比其他数都小的数:

float('-inf')

这在python2和python3中都有效。

sys。maxsize常量已从Python 3.0开始移除,取而代之的是使用sys.maxsize。

Integers PEP 237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type. ... The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).