整数的最大值和最小值

发布于 2024-12-07 04:46:49 字数 216 浏览 0 评论 0原文

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


另请参阅:Python 中的最大浮点数是多少?

How do I represent minimum and maximum values for integers in Python? In Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE.


See also: What is the maximum float in Python?.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

淡淡的优雅 2024-12-14 04:46:49

Python 3

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

但是,您实际上可能正在寻找有关当前解释器的字大小,在大多数情况下与机器的字长相同。该信息在 Python 3 中仍然可用 sys.maxsize,这是一个有符号字可以表示的最大值。同样,它是最大可能列表或内存序列的大小。

通常,无符号字可表示的最大值为 sys.maxsize * 2 + 1,字中的位数为 math.log2(sys.maxsize * 2 + 2)。有关详细信息,请参阅此答案

Python 2

在 Python 2 中,普通 int 值的最大值可用作 sys.maxint

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

可以用-sys.maxint - 1计算最小值,如图在文档中

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

Python 3

In Python 3, this question doesn't apply. The plain int type is unbounded.

However, you might actually be looking for information about the current interpreter's word size, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as sys.maxsize, which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory sequence.

Generally, the maximum value representable by an unsigned word will be sys.maxsize * 2 + 1, and the number of bits in a word will be math.log2(sys.maxsize * 2 + 2). See this answer for more information.

Python 2

In Python 2, the maximum value for plain int values is available as sys.maxint:

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

You can calculate the minimum value with -sys.maxint - 1 as shown in the docs.

Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.

归属感 2024-12-14 04:46:49

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

float('inf')

以类似的方式使用比所有其他数字都小的数字:

float('-inf')

这在 python 2 和 3 中都有效。

If you just need a number that's bigger than all others, you can use

float('inf')

in similar fashion, a number smaller than all others:

float('-inf')

This works in both python 2 and 3.

送舟行 2024-12-14 04:46:49

sys.maxint 常量 已从 Python 3.0 开始删除,而是使用 sys.maxsize

整数

  • PEP 237:本质上,长< /code> 重命名为 int。也就是说,只有一种内置整型,名为int;但它的行为大多类似于旧的 long 类型。

...

  • sys.maxint 常量已被删除,因为整数值不再有限制。但是, sys.maxsize 可以用作大于任何实际列表或字符串索引的整数。它符合实现的“自然”整数大小,通常与同一平台上以前版本中的 sys.maxint 相同(假设具有相同的构建选项)。

The sys.maxint constant has been removed from Python 3.0 onward, instead use 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).
墨落画卷 2024-12-14 04:46:49

对于 Python 3,int 类型没有最大值或最小值。

您可能对 sys.maxsize 相反。根据文档:

sys.maxsize

一个整数,给出 Py_ssize_t 类型的变量可以得到的最大值
拿。在 32 位平台上通常为 2**31 - 1,在 32 位平台上通常为 2**63 - 1
64 位平台。

import sys
max_size = sys.maxsize
min_size = -sys.maxsize - 1

For Python 3, there is no maximum or minimum value for the int type.

You might be interested in sys.maxsize instead. According to the documentation:

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.

import sys
max_size = sys.maxsize
min_size = -sys.maxsize - 1
不即不离 2024-12-14 04:46:49

在 Python 2 中,整数会自动从固定大小的 int 表示形式切换为可变宽度 long 表示,一旦您传递值 sys.maxint,为 231 - 1 或 263 - 1,具体取决于你的平台。请注意此处附加的 L

>>> 9223372036854775807
9223372036854775807
>>> 9223372036854775808
9223372036854775808L

来自 Python 2.7 手册

数字是由数字文字或内置函数和运算符的结果创建的。未经修饰的整数字面量(包括二进制、十六进制和八进制数字)生成普通整数,除非它们表示的值太大而无法表示为普通整数,在这种情况下它们生成长整数。带有 'L''l' 后缀的整数文字会产生长整数(首选 'L' 因为 1l > 看起来太像十一了!)。

Python 非常努力地假装它的整数是数学整数并且是无界的。例如,它可以轻松计算 googol

>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

In Python 2, integers will automatically switch from a fixed-size int representation into a variable width long representation once you pass the value sys.maxint, which is either 231 - 1 or 263 - 1 depending on your platform. Notice the L that gets appended here:

>>> 9223372036854775807
9223372036854775807
>>> 9223372036854775808
9223372036854775808L

From the Python 2.7 manual:

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an 'L' or 'l' suffix yield long integers ('L' is preferred because 1l looks too much like eleven!).

Python tries very hard to pretend its integers are mathematical integers and are unbounded. It can, for instance, calculate a googol with ease:

>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L
软的没边 2024-12-14 04:46:49

您可以像这样使用“inf”:

import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf

请参阅:数学 — 数学函数

You may use 'inf' like this:

import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf

Refer: math — Mathematical functions

恋竹姑娘 2024-12-14 04:46:49

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

np.iinfo(np.intp).max

这与 sys.maxsize 相同,但优点是您不需要为此导入 sys 。

如果您希望机器上的本机 int 最大:

np.iinfo(np.intc).max

您可以在 文档

对于浮点数,您还可以使用 sys.float_info.max 。

If you want the max for array or list indices (equivalent to size_t in C/C++), you can use numpy:

np.iinfo(np.intp).max

This is same as sys.maxsize however advantage is that you don't need import sys just for this.

If you want max for native int on the machine:

np.iinfo(np.intc).max

You can look at other available types in doc.

For floats you can also use sys.float_info.max.

渡你暖光 2024-12-14 04:46:49

在 64 位系统上的 CPython 3.11 上,最大和最小整数为

  2 ** ((2 ** 63 - 1) * 30) - 1
-(2 ** ( 2 ** 63      * 30) - 1)

您将需要 40 艾字节 内存来创建一个,这将成本700 亿美元 按今天计算(2023 年 7 月)NewEgg 上的价格为每 32GB 57 美元 ,因此实际上 Python 的最大整数受到计算机内存量的限制。


CPython 3.11 存储整数像这样(我通过删除所有宏来简化实际代码):

struct PyLongObject {
    Py_ssize_t ob_refcnt;  /* Metadata for garbage collection */
    PyTypeObject* ob_type; /* Metadata for type() */
    Py_ssize_t ob_size;    /* Number of items in ob_digit */
    uint32_t ob_digit[1];  /* Array of 32-bit integers */
};

所以在 64 位系统上, Python 整数被实现为 32 位整数数组,存储整数的绝对值(但每个整数的 2 位 未使用)和 64-位符号 二进制补码 整数存储该数组的长度以及 Python 整数的符号,因此负整数具有负“大小”。

On CPython 3.11 on a 64-bit system, the maximum and minimal integers are

  2 ** ((2 ** 63 - 1) * 30) - 1
-(2 ** ( 2 ** 63      * 30) - 1)

You will need 40 exabytes of memory to create one, which would cost $70 billion at today's (July 2023) prices of $57 per 32GB on NewEgg, so in practice Python's maximum integer is limited by how much memory you have in your computer.


CPython 3.11 stores integers like this (I simplified the actual code by taking out all the macros):

struct PyLongObject {
    Py_ssize_t ob_refcnt;  /* Metadata for garbage collection */
    PyTypeObject* ob_type; /* Metadata for type() */
    Py_ssize_t ob_size;    /* Number of items in ob_digit */
    uint32_t ob_digit[1];  /* Array of 32-bit integers */
};

So on a 64-bit system, Python integers are implemented as an array of 32-bit integers storing the absolute value of the integer (but 2 of the bits of each integer aren't used) and a 64-bit signed two's complement integer stores the length of that array as well as the sign of the Python integer, so a negative integer has a negative "size".

向日葵 2024-12-14 04:46:49

sys.maxsize 并不是实际支持的最大整数值。您可以将 maxsize 加倍并乘以它本身,它仍然是一个有效且正确的值。

但是,如果您尝试 sys.maxsize ** sys.maxsize,它会使您的计算机挂起相当长的时间。正如许多人指出的那样,字节和位大小似乎并不相关,因为它实际上不存在。我猜想当 python 需要更多内存空间时,它只是高兴地扩展它的整数。所以一般来说没有限制。

现在,如果您正在谈论以安全的方式打包或存储整数,以便稍后可以完整地检索它们,那么这当然是相关的。我真的不确定打包的事情,但我知道 python 的 pickle 模块可以很好地处理这些事情。字符串表示显然没有实际限制。

所以实际上,底线是:您的应用程序限制是什么?数字数据需要什么?使用该限制而不是 python 相当不存在的整数限制。

sys.maxsize is not the actually the maximum integer value which is supported. You can double maxsize and multiply it by itself and it stays a valid and correct value.

However, if you try sys.maxsize ** sys.maxsize, it will hang your machine for a significant amount of time. As many have pointed out, the byte and bit size does not seem to be relevant because it practically doesn't exist. I guess python just happily expands it's integers when it needs more memory space. So in general there is no limit.

Now, if you're talking about packing or storing integers in a safe way where they can later be retrieved with integrity then of course that is relevant. I'm really not sure about packing but I know python's pickle module handles those things well. String representations obviously have no practical limit.

So really, the bottom line is: what is your applications limit? What does it require for numeric data? Use that limit instead of python's fairly nonexistent integer limit.

梦魇绽荼蘼 2024-12-14 04:46:49

我非常依赖这样的命令。

python -c 'import sys; print(sys.maxsize)'

返回的最大整数:9223372036854775807

有关“sys”的更多参考,您应该访问

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html# sys.maxsize

I rely heavily on commands like this.

python -c 'import sys; print(sys.maxsize)'

Max int returned: 9223372036854775807

For more references for 'sys' you should access

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html#sys.maxsize

晨曦慕雪 2024-12-14 04:46:49

正如其他答案所指出的,与 float (其最大值为 sys.float_info.max)不同,int 类型在 Python 中是无界的;它实际上受到机器内存限制的限制。也就是说,存在一些与整数相关的限制。

例如,从 Python 3.10.7 开始,将 str 转换为 int 或打印 int 限制为 4300 位,其结果是编写一个默认情况下,文件中的超长整数受到限制(可以通过运行 sys.set_int_max_str_digits(0) 来关闭)。您可以使用 sys.int_info 获取有关 Python 中整数的内部表示形式的信息。

此外,由于 float 是有界的,因此您无法执行输出将成为浮点范围之外的浮点的计算(例如 2**1025/2 引发 溢出错误)。

另外,numpy、pandas等流行数据分析库中的int受到其类型的限制,例如numpy.uint64可以保存numpy中最大的正整数,这可以由np.iinfo('uint64')检查。这意味着我们无法执行涉及太大整数的矢量化计算,例如我们无法采用 2**64 的 log2(事实上,np.log2(2**64) 会引发 TypeError) 。

sys.maxsize 是最大可能列表的大小。您可以使用 range() 进行检查。

len(range(sys.maxsize)) == sys.maxsize    # 9223372036854775807
len(range(sys.maxsize+1))                 # OverflowError

As other answers point out, unlike float (which has the maximum value of sys.float_info.max), int type is unbounded in Python; it is really bounded by the memory limit of your machine. That said, there are some limits related to integers.

For example, since Python 3.10.7, converting str to int or printing int is limited to 4300 digits, a consequence of which is writing a very long integer to a file is limited by default (which can be turned off by running sys.set_int_max_str_digits(0)). You can get information about the internal representation of integers in Python using sys.int_info.

Also since float is bounded, you can't perform calculations where the output would become a float that is outside float bound (e.g. 2**1025/2 raises an OverflowError).

Also, int in popular data analysis libraries such as numpy and pandas etc. are bound by their type, e.g. numpy.uint64 can hold the largest positive integer in numpy, which can be checked by np.iinfo('uint64'). This means we can't perform vectorized computations involving too large integers, e.g. we can't take log2 of 2**64 (in fact, np.log2(2**64) raises a TypeError).

sys.maxsize is the size of the largest possible list. You can check that by using range().

len(range(sys.maxsize)) == sys.maxsize    # 9223372036854775807
len(range(sys.maxsize+1))                 # OverflowError
与风相奔跑 2024-12-14 04:46:49

下面给出的代码会对您有所帮助。
对于最大值,您可以使用sys.maxsize,对于最小值,您可以否定相同的值并使用它。

import sys 

ni=sys.maxsize
print(ni)

code given below will help you.
for maximum value you can use sys.maxsize and for minimum you can negate same value and use it.

import sys 

ni=sys.maxsize
print(ni)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文