我希望将一个值表示为64位带符号的long,这样大于(2**63)-1的值将表示为负值,但是Python long具有无限的精度。有没有一种“快速”的方法让我做到这一点?
发布于 2009-11-20 00:32:08
您可以使用ctypes.c_longlong
>>> from ctypes import c_longlong as ll
>>> ll(2 ** 63 - 1)
c_longlong(9223372036854775807L)
>>> ll(2 ** 63)
c_longlong(-9223372036854775808L)
>>> ll(2 ** 63).value
-9223372036854775808L如果您确定目标计算机上的signed long long将为64位宽,则这是真正的选项。
编辑:为64位数字定义一个类的 jorendorff's idea很吸引人。理想情况下,您希望最大限度地减少显式类创建的数量。
使用c_longlong,您可以这样做(注意:仅限Python3.x!):
from ctypes import c_longlong
class ll(int):
def __new__(cls, n):
return int.__new__(cls, c_longlong(n).value)
def __add__(self, other):
return ll(super().__add__(other))
def __radd__(self, other):
return ll(other.__add__(self))
def __sub__(self, other):
return ll(super().__sub__(other))
def __rsub__(self, other):
return ll(other.__sub__(self))
...这样,ll(2 ** 63) - 1的结果实际上就是9223372036854775807。但是,这种构造可能会导致性能损失,因此根据您到底想要做什么,定义像上面这样的类可能不值得。如果不确定,请使用timeit。
发布于 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
复制相似问题