mpfr
以下函数将返回两个对象的匹配位数。
import gmpy2
def matching_bits(x, y):
'''Returns the number of bits that match between x and y. The
sign of x and y are ignored. x and y must be of type mpfr.'''
# Force both values to be positive, and x >= y.
x = abs(x)
y = abs(y)
if x < y:
x, y = y, x
if not isinstance(x, type(gmpy2.mpfr(0))) or not isinstance(y, type(gmpy2.mpfr(0))):
raise TypeError("Arguments must be of type 'mpfr'.")
x_bits, x_exp, x_prec = x.digits(2)
y_bits, y_exp, y_prec = y.digits(2)
# (x_exp - y_exp) is the number of zeros that must be prepended
# to x to align the mantissas. If that is greater than the precision
# y, then no bits in common.
if (x_exp - y_exp) > x_prec:
return 0
x_bits = "0" * (x_exp - y_exp) + x_bits
count = 0
while count < min(x_prec, y_prec) and x_bits[count] == y_bits[count]:
count += 1
return count
我没有对这个功能进行广泛的测试,但它应该给你一个开始。您将需要分别检查实部和虚部。您可能需要对其进行修改以检查符号以及您是否正在执行加法与减法。