Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most negative value for python

Tags:

python

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?

like image 800
Cheok Yan Cheng Avatar asked Nov 22 '10 02:11

Cheok Yan Cheng


2 Answers

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
like image 164
the wolf Avatar answered Nov 03 '22 01:11

the wolf


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

like image 42
John La Rooy Avatar answered Nov 03 '22 01:11

John La Rooy