关于python:长整数的最大值

Maximum value for long integer

如何将长整数的最大值分配给变量,例如,类似于C ++的LONG_MAX


长整数:

没有明确定义的限制。可用地址空间量构成实际限制。
(取自本网站)。请参阅数字类型的文档,您将看到Long integers have unlimited precision。在Python 2中,当Integers超出限制时,它们会自动切换到long:

1
2
3
4
5
>>> import sys
>>> type(sys.maxsize)
<type 'int'>
>>> type(sys.maxsize+1)
<type 'long'>

对于整数我们有

maxint和maxsize:

可以在Python 2.x中找到int的最大值sys.maxint。它已在Python 3中删除,但通常可以使用sys.maxsize。来自更改日志:

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).

并且,对于任何对差异感兴趣的人(Python 2.x):

sys.maxint The largest positive integer supported by Python’s regular
integer type. This is at least 2**31-1. The largest negative integer
is -maxint-1 — the asymmetry results from the use of 2’s complement
binary arithmetic.

sys.maxsize The largest positive integer supported by the platform’s
Py_ssize_t type, and thus the maximum size lists, strings, dicts, and
many other containers can have.

为了完整起见,这是Python 3版本:

sys.maxsize
An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2^31 - 1 on a 32-bit platform and
2^63 - 1 on a 64-bit platform.

花车:

float("inf")float("-inf")。这些可以与其他数字类型进行比较:

1
2
3
>>> import sys
>>> float("inf") > sys.maxsize
True


Python long可以任意大。如果您需要一个大于任何其他值的值,则可以使用float('inf'),因为Python在比较不同类型的数值时没有任何问题。同样,对于小于任何其他值的值,您可以使用float('-inf')


直接回答标题问题:

整数大小不受限制,在Python中没有最大值。

回答哪些地址陈述了基本用例:

根据你对你要做的事情的评论,你现在正在思考一些事情

1
2
3
4
minval = MAXINT;
for (i = 1; i < num_elems; i++)
    if a[i] < a[i-1]
        minval = a[i];

这不是如何用Python思考的。更好的Python翻译(但仍然不是最好的)将是

1
2
3
minval = a[0]  # Just use the first value
for i in range(1, len(a)):
    minval = min(a[i], a[i - 1])

注意,上面根本不使用MAXINT。解决方案的这一部分适用于任何编程语言:您不需要知道最高可能值,只是为了找到集合中的最小值。

但无论如何,你在Python中真正做的只是

1
minval = min(a)

也就是说,你根本不写循环。内置的min()函数获得整个集合的最小值。


Python 2.x中的long类型使用任意精度算术,并且没有最大可能值。它受可用内存的限制。 Python 3.x对于无法用本机整数表示的值没有特殊类型 - 一切都是int,转换是在幕后处理的。


与C / C ++不同,Python中的Long具有无限的精度。有关更多信息,请参阅python中的数字类型部分。要确定整数的最大值,您可以参考sys.maxint。您可以从sys的文档中获取更多详细信息。


你可以使用:浮点数的最大值是

1
float('inf')

为负面

1
float('-inf')


在python3中,您可以将浮点值发送到int函数中,以整数表示形式获取该数字1.7976931348623157e + 308。

1
2
import sys    
int(sys.float_info.max)