简体   繁体   中英

Why isn't Python throwing an overflow error?

I'm learning Python and I have a question about the range of the data types.

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() ? My CPU cannot handle integers with more than 64 bits, so I expect the operation to produce an overflow.

The Python long integer type is only limited by your available memory. 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. In Python 3, all integers are long integers; there is no distinction.

Python knows two data types for integers: int and long . If a number is too large for an int (64 bit), then automatically a long is used. Also if the result of a computation is too large for an int , a long is used instead.

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). So, 5L is a long .

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

long s aren't limited in any particular number of bits. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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