一、int
1.int.bit_length()
获取数字的二进制表示长度
例子:
>>>bin(10)
'0b1010'
>>>int.bit_length(10)
4
方法等价于:
def bit_length(self):
s = bin(self) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
2.int.to_bytes(length, byteorder, *, signed=False)
将数字转换为十六进制表示,
length
代表将要转换的数据长度,不足补0,超出报错(OverflowError
)
byteorder
表示转换后的数字的排列顺序,big
表示正常表示,little
表示反向表示
signed
如果传入的是负数或者其他会引起OverflowError
的数字,则设置signed
为True
可避免报错
例子:
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'
3.int.from_bytes(bytes, byteorder, *, signed=False
将byte-like类型的十六进制数字转换为十进制表示,
bytes
代表要转换的数据
byteorder
表示bytes
的读取顺序,big
表示正常读取,little
表示反向读取
signed
设置signed
为True
表示返回的是负数表示
例子:
>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680
二、float
1.float.as_integer_ratio()
返回一对整数,其比值与原浮点数完全相等,且具有正分母
传入必须为浮点数,否则会报错TypeError
>>>float.as_integer_ratio(1.5)
(3, 2)
>>>float.as_integer_ratio(2)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: descriptor 'as_integer_ratio' requires a 'float' object but received a 'int'
>>>float.as_integer_ratio(2.0)
(2, 1)
>>>float.as_integer_ratio(2.1)
(4728779608739021, 2251799813685248)
2.float.is_integer()
判断浮点数是否是整数
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
3.float.hex()
浮点数转化为十六进制的浮点数...
>>>float.hex(1.0)
'0x1.0000000000000p+0'
>>>float.hex(2.1)
'0x1.0cccccccccccdp+1'
4.float.fromhex(s)
十六进制转化为浮点数
>>> float.fromhex('0x3.a7p10')
3740.0
>>> float.hex(3740.0)
'0x1.d380000000000p+11'
>>>float.fromhex('0x1.0cccccccccccdp+1')
2.1
三、数字的hash值(Hashing of numeric types)
python 官方文档上写的:
python定义的hash值的计算规则:
- If
x = m / n
is a nonnegative rational number andn
is not divisible byP
, definehash(x)
asm * invmod(n, P) % P
, whereinvmod(n, P)
gives the inverse ofn
moduloP
. - If
x = m / n
is a nonnegative rational number andn
is divisible byP
(butm
is not) thenn
has no inverse moduloP
and the rule above doesn’t apply; in this case definehash(x)
to be the constant valuesys.hash_info.inf
. - If
x = m / n
is a negative rational number definehash(x)
as-hash(-x)
. If the resulting hash is-1
, replace it with-2
. - The particular values
sys.hash_info.inf
,-sys.hash_info.inf
andsys.hash_info.nan
are used as hash values for positive infinity, negative infinity, or nans (respectively). (All hashable nans have the same hash value.) - For a
complex
numberz
, the hash values of the real and imaginary parts are combined by computinghash(z.real) +sys.hash_info.imag * hash(z.imag)
, reduced modulo2**sys.hash_info.width
so that it lies inrange(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1))
. Again, if the result is-1
, it’s replaced with-2
.
下面是根据上面的设定的规则实现的计算hash的方法
import sys, math
def hash_fraction(m, n):
"""Compute the hash of a rational number m / n.
Assumes m and n are integers, with n positive.
Equivalent to hash(fractions.Fraction(m, n)).
"""
P = sys.hash_info.modulus
# Remove common factors of P. (Unnecessary if m and n already coprime.)
while m % P == n % P == 0:
m, n = m // P, n // P
if n % P == 0:
hash_value = sys.hash_info.inf
else:
# Fermat's Little Theorem: pow(n, P-1, P) is 1, so
# pow(n, P-2, P) gives the inverse of n modulo P.
hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
if m < 0:
hash_value = -hash_value
if hash_value == -1:
hash_value = -2
return hash_value
def hash_float(x):
"""Compute the hash of a float x."""
if math.isnan(x):
return sys.hash_info.nan
elif math.isinf(x):
return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
else:
return hash_fraction(*x.as_integer_ratio())
def hash_complex(z):
"""Compute the hash of a complex number z."""
hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
# do a signed reduction modulo 2**sys.hash_info.width
M = 2**(sys.hash_info.width - 1)
hash_value = (hash_value & (M - 1)) - (hash_value & M)
if hash_value == -1:
hash_value = -2
return hash_value
网友评论