我正在尝试计算到非常大的数(<= 10 ^ 19)的最接近的2 ^ n
我尝试使用math.log(number,2)。但这对于很大的数字给出了错误的结果。在不使用其他库的情况下应该如何做?
a = 9843649374639837463 # a is any num between 1 and 10^9
number = int(math.log(a,2))
答案 0 :(得分:6)
大整数输入正以有限的精度转换为浮点数,因此s ome input precision is being lost。另外,math.log2()比 math.log()更准确,因为它针对基数2进行了微调。
有一种 int 方法可以准确无误地bit_length():
>>> a = 9843649374639837463
>>> a.bit_length()
64
>>> bin(a)
'0b1000100010011011101010101111001111001100111001110101000100010111'
请注意,浮点日志非常接近,但不完全正确:
>>> a = 9843649374639837463
>>> 2.0 ** math.log2(a)
9.843649374639845e+18
>>> abs(a - 2.0 ** math.log2(a))
8192.0