python整数怎么表示_python怎么创建无穷大整数

python2里能不能用sys.maxint来表示无穷大呢

使用sys.maxint不能表示无穷大,sys.maxint + 1 > sys.maxint 得到的结果为True

有没有类似float('inf')的方法创建一个无穷大的整数

因为python里没有限制int表示整型的边界,int可以存放任意大的整数,所以用整型数值表示不出一个无穷大。

在Java里int表示范围是有限制的,范围是-2147483648 到2147483648,所以可以使用边界值的数值表示最大值和最小值:

public static final int MIN_VALUE = 0x80000000;

public static final int MAX_VALUE = 0x7fffffff;

在python创建一个无穷大或者无穷小的整型,需要看使用场景。如果是用于比较,任何整数N < +Infinity结果为True,可以自定义一个类,用于和其他整数比较:

import functools

@functools.total_ordering

class NeverSmaller(object):

def __le__(self, other):

return False

class ReallyMaxInt(NeverSmaller, int):

def __eq__(self, other):

return isinstance(other, ReallyMaxInt)

def __repr__(self):

return 'ReallyMaxInt()'

使用:

>>> N = ReallyMaxInt()

>>> N > sys.maxsize

True

>>> isinstance(N, int)

True

>>> sorted([1, N, 0, 9999, sys.maxsize])

[0, 1, 9999, 9223372036854775807, ReallyMaxInt()]

注意:functools.total_ordering 是禁止继承int的已有的排序方法。