I expect the most negative for python is -maxint-1
I expect having -2, will make integer overflow.
from sys import maxint
maximum_int = maxint
minimum_int = -maxint - 2
# 2147483647
# -2147483649
print maximum_int
print minimum_int
Yet. Correct result is displayed, and a value which is more negative than -maxint-1
is shown.
May I know why?
Here you can see the result is promoted to a long
>>> from sys import maxint
>>> type(-maxint)
<type 'int'>
>>> type(-maxint-1)
<type 'int'>
>>> type(-maxint-2)
<type 'long'>
>>>
note that the usual convention for signed values is to have one more negative number than positive, so in this case -2147483648
is still an int
In Python, int
s will auto-promote to long
(bigint).
Python autopromotes int
values that overflow to long
, which does not have a limit other than available memory.
Python promotes an overflow of int
to an arbitrary precision long which is limited only by available memory.
You can see the promotion with this code:
import struct
from sys import maxint
maximum_int = maxint
minimum_int = -maxint-1
big_minus = -maxint-(maxint*maxint)
big_plus=maxint*maxint*maxint
def platform():
return struct.calcsize("P") * 8
def bit_length(x):
s=bin(x)
s=s.lstrip('-0b')
return len(s)
print
print 'running in ', platform(), ' bit mode...'
print 'maxint: ', maximum_int, ' bits: ', bit_length(maximum_int)
print 'minint: ', minimum_int, ' bits: ', bit_length(minimum_int)
print 'a big minus: ', big_minus, ' bits: ', bit_length(big_minus)
print 'big_plus: ', big_plus, ' bits: ', bit_length(big_plus)
print
Running under 32 bit Python, here is the return:
running in 32 bit mode...
maxint: 2147483647 bits: 31
minint: -2147483648 bits: 32
a big minus: -4611686016279904256 bits: 62
big_plus: 9903520300447984150353281023 bits: 93
Under 64 bit Python:
running in 64 bit mode...
maxint: 9223372036854775807 bits: 63
minint: -9223372036854775808 bits: 64
a big minus: -85070591730234615856620279821087277056 bits: 126
big_plus: 784637716923335095224261902710254454442933591094742482943 bits: 189
Python implements biging concept, the type is called long. The size is unlimited virtually.
for Python 3,
import sys
""" max negative number """
print(sys.maxsize * -1)
"""through python's internal casts from int to long"""
print(sys.maxsize * -1 + 1)
"""
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).
[1]: https://docs.python.org/3.1/whatsnew/3.0.html#integers
"""
If you actually want the most negative value for python, float('-inf') works nicely.