我希望将一个值表示为64位带符号的long
,这样大于(2**63)-1
的值将表示为负值,但是Python long
具有无限的精度。有没有一种“快速”的方法让我做到这一点?
发布于 2009-11-20 08:28:00
你会用numpy吗?它有一个int64类型,可以执行您想要的操作。
In [1]: import numpy
In [2]: numpy.int64(2**63-1)
Out[2]: 9223372036854775807
In [3]: numpy.int64(2**63-1)+1
Out[3]: -9223372036854775808
与ctypes示例不同,它对用户是透明的,而且它是用C编写的,所以它比用Python编写自己的类要快。Numpy可能比其他解更大,但如果你在做数值分析,你会喜欢它的。
发布于 2009-11-20 00:30:23
最快的方法可能是自己将结果截断为64位:
def to_int64(n):
n = n & ((1 << 64) - 1)
if n > (1 << 63) - 1:
n -= 1 << 64
return n
当然,您可以定义自己的数字类型,每次执行任何类型的算术操作时都会自动执行此操作:
class Int64:
def __init__(self, n):
if isinstance(n, Int64):
n = n.val
self.val = to_int64(n)
def __add__(self, other):
return Int64(self.val + other)
def __radd__(self, other):
return Int64(other + self.val)
def __sub__(self, other):
return Int64(self.val - other)
...
但这并不是特别“快速”的实现。
https://stackoverflow.com/questions/1764548
复制相似问题