python的最负值

时间:2010-11-22 02:44:41

标签: python

我预计python最负面的是-maxint-1

我希望有-2,会使整数溢出。

from sys import maxint
maximum_int = maxint
minimum_int = -maxint - 2
#  2147483647
# -2147483649
print maximum_int
print minimum_int

然而。显示正确的结果,并显示比-maxint-1更负的值。

我可以知道为什么吗?

7 个答案:

答案 0 :(得分:16)

在这里你可以看到结果被提升为长

>>> from sys import maxint
>>> type(-maxint)
<type 'int'>
>>> type(-maxint-1)
<type 'int'>
>>> type(-maxint-2)
<type 'long'>
>>> 

请注意,有符号值的通常约定是多一个负数而不是正数,所以在这种情况下-2147483648仍然是一个整数

答案 1 :(得分:5)

在Python中,int会自动提升为long(bigint)。

答案 2 :(得分:2)

Python autopromotes int值溢出到long,除了可用内存之外没有其他限制。

答案 3 :(得分:1)

Python将int的溢出提升为任意精度长度,仅受可用内存的限制。

您可以使用以下代码查看促销:

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

在32位Python下运行,这是返回:

running in    32  bit mode...
maxint:       2147483647  bits:  31
minint:       -2147483648  bits:  32
a big minus:  -4611686016279904256  bits:  62
big_plus:     9903520300447984150353281023  bits:  93

在64位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

答案 4 :(得分:0)

Python实现了biging概念,类型称为long。尺寸无限制。

答案 5 :(得分:0)

如果你真的想要python的最负值,那么float(' - inf')效果很好。

答案 6 :(得分:0)

对于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
"""