长整数的最大值

2024-04-26 07:02:13 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将长整数的最大值分配给变量,类似的,例如,C++的^ {CD1>}。


Tags: 整数cd1
3条回答

直接回答标题问题:

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

回答哪个地址说明了底层用例:

根据你对你所要做的事情的评论,你目前的想法是

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

这不是Python中的思维方式。更好的Python翻译(但仍然不是最好的)是

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

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

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

minval = min(a)

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

长整数:

没有明确定义的限制。可用地址空间的数量构成了一个实际的限制。
(取自this站点)。查看Numeric Types上的文档,您将在其中看到Long integers have unlimited precision。在Python2中,当整数增长超过其限制时,它们将自动切换到long:

>>> import sys
>>> type(sys.maxsize)
<type 'int'>
>>> type(sys.maxsize+1)
<type 'long'>


对于整数我们有

maxint和maxsize:

int的最大值可以在Python 2.x中找到,sys.maxint。它在Python 3中被删除,但是sys.maxsize通常可以被使用。来自the changelog

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

the difference(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 version

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")。这些可以与其他数字类型进行比较:

>>> import sys
>>> float("inf") > sys.maxsize
True

Pythonlong可以任意大。如果需要大于任何其他值的值,可以使用float('inf'),因为Python比较不同类型的数值没有问题。类似地,对于小于任何其他值的值,可以使用float('-inf')

相关问题 更多 >