简体   繁体   English

为什么Python不会抛出溢出错误?

[英]Why isn't Python throwing an overflow error?

I'm learning Python and I have a question about the range of the data types. 我正在学习Python,我对数据类型的范围有疑问。

This program: 这个程序:

print("8 bits:", pow(2, 8)-1)
print("16 bits:", pow(2, 16)-1)
print("32 bits:", pow(2, 32)-1)
print("64 bits:", pow(2, 64)-1)

print( pow(18446744073709551615+18446744073709551615+2, 9) )

Produces the following output: 产生以下输出:

8 bits: 255
16 bits: 65535
32 bits: 4294967295
64 bits: 18446744073709551615
12663316555422952143897729076205936129798725073982046203600028471956337925454431
59912019973433564390346740077701202633417478988975650566195033836314121693019733
02667340133957632

My question is: how can Python calculate the result of the last call to pow() ? 我的问题是:Python如何计算上次调用pow() My CPU cannot handle integers with more than 64 bits, so I expect the operation to produce an overflow. 我的CPU无法处理超过64位的整数,所以我希望操作产生溢出。

The Python long integer type is only limited by your available memory. Python长整数类型仅受可用内存的限制。 Until you run out of memory, the digits will just keep on coming. 直到你的内存不足,数字才会继续。

Quoting from the numeric types documentation : 引用数字类型文档

Long integers have unlimited precision. 长整数具有无限精度。

Python will transparently use long integers when you need the unlimited precision. 当您需要无限精度时,Python将透明地使用长整数。 In Python 3, all integers are long integers; 在Python 3中,所有整数都是长整数; there is no distinction. 没有区别。

Python knows two data types for integers: int and long . Python知道整数的两种数据类型: intlong If a number is too large for an int (64 bit), then automatically a long is used. 如果一个数字对于int (64位)来说太大,则自动使用long Also if the result of a computation is too large for an int , a long is used instead. 此外,如果计算结果对于int来说太大,则使用long

You can explicitly declare a literal to be a long; 你可以明确地声明一个文字是长的; just add an L to it (an l also is possible but is discouraged because in many fonts this is indistinguishable or at least very much alike a 1 (one) character). 只需添加一个L (也可以使用l但不鼓励,因为在许多字体中,这是无法区分的,或者至少非常类似于1 (一个)字符)。 So, 5L is a long . 所以, 5Llong

Typically this distinction is not important; 通常这种区别并不重要; to know of the difference will become necessary, though, if you compare the types of values (because type(5)type(5L) ). 但是,如果比较值的类型(因为type(5)type(5L) ),知道差异将是必要的。

long s aren't limited in any particular number of bits. long s不限于任何特定数量的比特。 At ridiculous high values, the memory consumption and the computation times pose a practical limit, though. 然而,在荒谬的高值下,内存消耗和计算时间构成了实际限制。

Also keep in mind that computing stuff with these long might be faster than print ing them because when converting them to a string for the printing, they have to be converted into the decimal system. 还要记住,计算具有这些long东西可能比print它们更快,因为在将它们转换为字符串进行打印时,它们必须转换为十进制系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM